天天看點

iOS 面試題~經驗找代碼錯誤

//聯系人:石虎 QQ:1224614774 昵稱:嗡嘛呢叭咪哄

一、概念

1.指出以下這段代碼的問題

 - (void)test{

    CGRect frame = CGRectMake(20, 200, 200, 20);

    self.alert = [[UILabel alloc]initWithFrame:frame];

    self.alert.text =@"Please wait 10 seconds...";

    self.alert.textColor = [UIColor redColor];

    [self.view addSubview:self.alert];

    NSOperationQueue *waitQueue = [[NSOperationQueuealloc]init];

    [waitQueue addOperationWithBlock:^{

        [NSThreadsleepUntilDate:[NSDatedateWithTimeIntervalSinceNow:10]];

        self.alert.text = @"石虎";

        NSLog(@"執行一個新的操作,線程:%@", [NSThread currentThread]);

    }];

}

正确修改為:

 [waitQueue addOperationWithBlock:^{

        [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]];

    //正确要在主線程賦

    dispatch_async(dispatch_get_main_queue(), ^{

        self.alert.text = @"石虎";

    });

    NSLog(@"執行一個新的操作,線程:%@", [NSThread currentThread]);

}];

2.寫出下列程式的輸出結果

typedef void (^BoringBlock)(void);

int main(int argc,constchar *argv[])

{

    int a = 23;

    __block int b =23;

    BoringBlock block1 = ^{NSLog(@"a1==%d",a);};

    BoringBlock block2 = ^{NSLog(@"b1==%d",b);};

    a = 32;

    b = 32;

    BoringBlock block3 = ^{NSLog(@"a1==%d",a);};

    BoringBlock block4 = ^{NSLog(@"b2==%d",b);};

    block1();

    block2();

    block3();

    block4();

    return 0;

}

列印結果:

2017-10-3020:29:25.645 石虎測試 demo[969:6507971] a1==23

2017-10-3020:29:25.646 石虎測試 demo[969:6507971] b1==32

2017-10-3020:29:25.646 石虎測試 demo[969:6507971] a1==32

2017-10-3020:29:25.646 石虎測試 demo[969:6507971] b2==32

謝謝!!!