本文介绍了从completionHandler 内部调用UIView 相关调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am calling the following Class method from within my ViewController init method:

[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 元素?

This code working as intended and tableView refreshes appropriately, My concern: is this call thread safe?. is it ok to access an UI element from the completion block?

谢谢,

维诺德

推荐答案

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

Actually, this is not correct unless opQueue happens to be +[NSOperationQueue mainQueue]

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

That completion block will be scheduled on the queue you provide. In your case, you're calling that queue 'opQueue'. If that queue is being drained by some thread other than the main thread, then you shouldn't make that call to reload the tableview there.

你应该做任何你需要做的处理,然后在主队列中加入另一个调用重新加载的块.

You should instead do whatever processing you need to do and then enqueue another block on the main queue which calls the reload.

^(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' 传递;

Or if the processing is light and quick (and fixed amount of time), then just pass the mainQueue as the 'opQueue';

我希望这是有道理的.在这里可以找到很多很好的信息:并发编程指南

I hope that makes sense. A lot of good information to be found here: Concurrency Programming Guide

这篇关于从completionHandler 内部调用UIView 相关调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!