可能重复:
Grand Central Dispatch (GCD) 与 performSelector - 需要更好的解释
要在主线程上执行“东西”,我应该使用dispatch_async
orperformSelectorOnMainThread
吗?是否有首选方法、正确/错误和/或最佳实践?
示例:我正在方法块中执行一些逻辑NSURLConnection sendAsynchronousRequest:urlRequest
。因为我正在对主视图做一些事情,例如呈现一个UIAlertView
我需要UIAlertView
在主线程上显示的东西。为此,我使用以下代码。
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// code snipped out to keep this question short
if(![NSThread isMainThread])
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"Some Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
});
}
}];
在同一个if(![NSThread isMainThread])
语句中,我还调用了一些自定义方法。问题是,我应该dispatch_async
使用上面使用的方法还是改用更好performSelectorOnMainThread
?例如,下面的完整代码:
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// code snipped out to keep this question short
if(![NSThread isMainThread])
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"Some Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
// call custom methods in dispatch_async?
[self hideLoginSpinner];
});
// or call them here using performSelectorOnMainThread???
[self performSelectorOnMainThread:@selector(hideLoginSpinner) withObject:nil waitUntilDone:NO];
}
}];
仅供参考 - 如果我不在他的主线程上执行这些操作,我会在呈现时看到几秒钟的延迟,UIAlertView
并且我在调试器中收到以下消息wait_fences: failed to receive reply: 10004003
。我了解到这是因为您需要在主线程上对 UI 进行更改...如果有人想知道我为什么要做我正在做的事情...