从completionHandler中调用UIView相关的调用?

我从我的ViewController init方法中调用以下Class方法:

[NSURLConnection sendAsynchronousRequest:urlrequest queue:opQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError*error){ // Update an NSMutableArray (an Instance variable [self tableView] reloadData]; // is this ok to call? }]; 

这段代码按预期工作,tableView适当刷新,我担心:这个调用线程安全吗? 从完成块访问UI元素是否可以?

谢谢,

维诺德

实际上,这是不正确的,除非opQueue碰巧是+ [NSOperationQueue mainQueue]

该完成块将安排在您提供的队列中。 在您的情况下,您正在调用该队列’opQueue’。 如果该队列被主线程以外的某个线程耗尽,那么您不应该进行该调用以在那里重新加载tableview。

您应该执行您需要执行的任何处理,然后将另一个块排入主队列,该块调用重新加载。

 ^(NSURLResponse *response, NSData *data, NSError*error){ // Do some processing work in your completion block dispatch_async(dispatch_get_main_queue(), ^{ // Back on the main thread, ask the tableview to reload itself. [someTableView reloadData]; }); } 

或者如果处理轻快(并且固定的时间量),那么只需将mainQueue作为’opQueue’传递;

我希望这是有道理的。 这里有很多好的信息: 并发编程指南

它是线程安全的。 非常因为你没有使用线程。 稍后调用完成处理程序,而不是在单独的线程上调用。