前段时间面试看到这么一道题
下面代码中有什么bug?
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *alertLabel = [[UILabel alloc] initWithFrame:CGRectMake(100,100,100,100)];
alertLabel.text = @"Wait 4 seconds...";
[self.view addSubview:alertLabel];
NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init];
[backgroundQueue addOperationWithBlock:^{
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:4]];
alertLabel.text = @"Ready to go!";
}];
}
Bug在于,在等了4秒之后,alertLabel并不会更新为Ready to Go。
原因是,所有UI的相关操作应该在主线程进行。当我们可以在一个后台线程中等待4秒,但是一定要在主线程中更新alertLabel。
最简单的修正如下:
- (void)viewDidLoad {
UILabel *alertLabel = [[UILabel alloc] initWithFrame:CGRectMake(100,100,100,100)];
alertLabel.text = @'Wait 4 seconds...';
[self.view addSubview:alertLabel];
NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init];
[backgroundQueue addOperationWithBlock:^{
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:4]];
//回到主线程刷新UI
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
alertLabel.text = @'Ready to go!”
}];
}];
}
网友评论