【问题标题】:iOS threading - callback best practiceiOS 线程 - 回调最佳实践
【发布时间】:2012-03-15 08:15:55
【问题描述】:

我想清理我的一个项目,并在一个类中提取我经常重复使用的部分源代码。 这个类处理一些对 Web 服务的请求,到目前为止一切都很好;)。在我将代码提取到它自己的类之前,我使用调用类中的线程和回调来处理这些请求。

现在我有一个“最佳实践”问题:

在我的代码中,我做了类似(简化)的事情:

(void)foo{
   Helper *h =[[Helper alloc]init];
  [h doRequest];
}

doRequest 执行一个网络操作(在它自己的类中),我必须等到这个请求完成。所以我需要一个回调或类似的东西。

我是否应该简单地线程 doRequest 包括。 waituntildone=YES?

我是否也必须在 Helper 类中线程化网络?或者像这样调用线程化的方法就足够了:

[NSThread detachNewThreadSelector:@selector(h doRequest) toTarget:self withObject:nil];

在调用者类完成任务后,从 doRequest 获取回调到调用者类的最佳做法是什么,以便我可以处理来自 Web 服务的返回值?

提前致谢。

约翰内斯

【问题讨论】:

    标签: objective-c ios multithreading networking


    【解决方案1】:

    鉴于 doRequest 在请求完成之前不会返回,您可以这样做

    - (void)fooCompletion:(void (^)(void))completion {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            Helper *h =[[Helper alloc]init];
            [h doRequest];
            if (completion) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    // doRequest is done
                    completion();
                });
            }
        });
    }
    

    调用方法:

    [self fooCompletion:^{
        // do something after doRequest is done
    }];
    

    【讨论】:

      【解决方案2】:

      我个人更喜欢在任何需要发回信息的辅助线程结束时调用 performSelectorOnMainThread:withObject:waitUntilDone:。

      [self performSelectorOnMainThread:@selector(infoFromService:) withObject:aDictionaryWithInfo waitUntilDone:NO];
      
      - (void)infoFromService:(NSDictionary *)aDictionary {
          //Process all the information and update UI
      }
      

      确保始终使用主线程进行任何 UI 更新,即使它们发生在工作线程的中间,例如更新已下载信息量的计数。使用相同的技术调用具有相关信息的主线程。

      【讨论】:

        猜你喜欢
        • 2010-10-14
        • 1970-01-01
        • 2014-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多