Objective-C Basics
- 下面代码中有什么bug?
* - (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]];
* 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]];
* [[NSOperationQueue mainQueue] addOperationWithBlock:^{
* alertLabel.text = @"Ready to go!”
* }];
* }];
* }
上一题 | 目录 | 下一题 |
---|
网友评论