我正在编写一个简单的天气应用程序来巩固我对协议(protocol)和代表的理解。我处于以下情况:
最好的方法是什么?我正在考虑嵌套委托(delegate)方法,其中数据源 1 在有数据时会通知数据源 2(通过协议(protocol)),然后让数据源 2 在有数据时通知 View Controller 更新 View 。但是,我认为这不是正确/最佳的做事方式。
有任何想法吗?
谢谢
最佳答案
这听起来很适合 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
});
有关详细信息,请参阅文档:https://developer.apple.com/library/ios/documentation/Performance/Reference/GCD_libdispatch_Ref/#//apple_ref/doc/uid/TP40008079-CH2-SW19
关于ios - 如何在 iOS 中同步两个异步委托(delegate)方法回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27242379/