Joh*_*ler 3 objective-c grand-central-dispatch ios
Objective-C Gurus,
我一直在使用以下宏来确保在主线程上运行块.这个想法很简单:如果我目前在主线程上,那么我将立即运行该块.如果当前线程不是主线程,那么我将块排队以在主线程上异步运行(这样它就不会阻塞当前线程).
你觉得这有什么问题吗?这里有什么不安全的,或导致我不知道的错误?有没有更好的方法呢?
#define run_on_main(blk) if ([NSThread isMainThread]) { blk(); } else { dispatch_async(dispatch_get_main_queue(), blk); }
Run Code Online (Sandbox Code Playgroud)
用法示例:
-(BOOL)loginCompletedSuccessfully
{
NSLog(@"loginCompletedSuccessfully");
// This may be called from a network thread, so let's
// ensure the rest of this is running on the main thread.
run_on_main(^{
if (_appStartupType == AppLaunch) {
self.storyboard = [UIStoryboard storyboardWithName:DEVICED(@"XPCStoryboard") bundle:nil];
self.navigationController = [storyboard instantiateInitialViewController];
}
[self.window setRootViewController:self.navigationController];
});
return YES;
}
Run Code Online (Sandbox Code Playgroud)
这有可能出现令人讨厌的执行顺序的细微错误.
拿这个简单的例子(在主线程上)
__block NSInteger integer = 5;
run_on_main(^{
integer += 10;
});
NSLog(@"From Main %d", integer);
Run Code Online (Sandbox Code Playgroud)
这将打印结果 15
相同的代码在后台线程中运行
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
__block NSInteger integer = 5;
run_on_main(^{
integer += 10;
});
NSLog(@"From background %d", integer);
});
Run Code Online (Sandbox Code Playgroud)
结果将是5...或15取决于线程之间的竞争条件.
这种不一致可能会让你失望.
为什么不在dispatch_async这两种情况下使用,并且知道两者现在都表现出相同的行为是安全的.这是安全和罚款,因为您正在使用async非阻塞
| 归档时间: |
|
| 查看次数: |
430 次 |
| 最近记录: |