我正在从我的 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”传递;

我希望这是有道理的。在这里可以找到很多好的信息:Concurrency Programming Guide

关于ios - 从completionHandler 内部调用UIView 相关调用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8450056/

10-12 00:18
查看更多