我正在学习Objective-C,并试图更好地理解GCD。我创建了一个可以进行API调用的对象(APICaller
),然后向其代理提供信息。在此对象的代理(TableViewControllerA
)viewDidLoad
方法中,我调用APICaller
的方法之一,然后使用该信息更新两个静态单元的detailTextLabel.text
。我的问题:为什么当我使用dispatch_async
时,detailTextLabel.text
的更新速度比没有更快?为什么GCD使这段代码正常工作?
这将更新细胞,但有一个较长时间的延迟:
- (void)viewDidLoad
{
APICaller *apiCaller = [APICaller alloc] init];
[apiCaller getInformationWithArgument:self.argument completionHandler:^(NSString *results, NSError *error) {
_staticCell.detailTextLabel.text = results;
}
}
...而这将更新单元格瞬间:
- (void)viewDidLoad
{
APICaller *apiCaller = [APICaller alloc] init];
[apiCaller getInformationWithArgument:self.argument completionHandler:^(NSString *results, NSError *error) {
dispatch_async(dispatch_get_main_queue, ^(void) {
_staticCell.detailTextLabel.text = results;
});
}
}
简单。所有UI更新必须在主线程上完成,并且完成处理程序不在主线程上。 – rmaddy 2014-10-30 14:17:07