子线程中不能直接更新UI,如果直接更新的话会发生崩溃
所以要在主线程中更新UI,总计三种回到主线程更新UI的方式
1、NSThread级主线程同步:performSelectorOnMainThread
NSOperationQueue *waitQueue = [[NSOperationQueue alloc] init];
[waitQueue addOperationWithBlock:^
{
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]];
// 同步到主线程
[self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
}];
UI更新方法
- (void)updateUI
{
self.text = @"Thanks!";
}
2、NSOperationQueue级主线程同步:[NSOperationQueue mainQueue]
NSOperationQueue *waitQueue = [[NSOperationQueue alloc] init];
[waitQueue addOperationWithBlock:^
{
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]];
// 同步到主线程
[[NSOperationQueue mainQueue] addOperationWithBlock:^
{
self.text = @"Thanks!";
}];
}];
3、GCD级主线程同步:dispatch_get_main_queue
NSOperationQueue *waitQueue = [[NSOperationQueue alloc] init];
[waitQueue addOperationWithBlock:^
{
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]];
// 同步到主线程
dispatch_async(dispatch_get_main_queue(), ^
{
self.text = @"Thanks!";
});
}];
网友评论