如何在iOS中同步两个异步委托方法回调?

p0n*_*0ny 1 protocols objective-c ios

我正在编写一个简单的天气应用程序,试图巩固我对协议和代表的理解.我遇到以下情况:

  • 我有两个数据源用于天气数据(此时只是NSObjects)和一个视图控制器,一旦我从两个源接收数据,我想要更新.
  • 这2个数据源具有我在视图控制器中遵守的协议.一旦他们从他们自己的Web服务接收数据,就会调用他们的委托方法.这可能意味着数据源1在数据源2之前获取数据,反之亦然,或同时获取数据(如果可能,则不知道100%)
  • 我只想在收到两个来源的数据后更新视图.

最好的方法是什么?我正在考虑嵌套委托方法,其中数据源1在有数据(通过协议)时通知数据源2,然后让数据源2通知视图控制器在有数据时更新视图.但是,我认为这不是正确/最好的做事方式.

有任何想法吗?

谢谢

小智 5

这听起来非常适合GCD调度组.

首先,创建一个调度组dispatch_group_create.然后dispatch_group_enter在开始每个服务的请求之前使用.dispatch_group_leave当您收到每项服务的回复时,请致电.您可以指定在两个请求完成时要执行的操作dispatch_group_notify.

代码可能如下所示:

dispatch_group_t weatherGroup = dispatch_group_create();

dispatch_group_enter(weatherGroup);
[weatherService1 requestWithCompletion:^(Response *response){
    // Do something with the response
    dispatch_group_leave(weatherGroup);
}];

dispatch_group_enter(weatherGroup);
[weatherService2 requestWithCompletion:^(Response *response){
    // Do something with the response
    dispatch_group_leave(weatherGroup);
}];

dispatch_group_notify(weatherGroup, dispatch_get_main_queue(),^{
    // This is executed after both requests are finished
});
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅文档:https://developer.apple.com/library/ios/documentation/Performance/Reference/GCD_libdispatch_Ref/#//apple_ref/doc/uid/TP40008079-CH2-SW19