我有一个异步的方法,如何在多次并发后得到全部结束的通知


第三方sdk有个异步上传方法 [UploadManager upload],但是只能单文件上传,要批量上传,得多次调用这个方法。现在我想得到他们全部结束的通知。

我尝试了用gcd group的方法,


 dispatch_group_t group = dispatch_group_create();
for (NSData *data in array) {
     dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
        [UploadManager upload];    
     });
}


 dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{
      // 汇总结果
 });

但是因为[UploadManager upload]是异步的,汇总结果总是一开始就先执行了。有什么办法解决吗?

gcd ios objective-c

6885789 10 years, 5 months ago

设个计数器,再弄个通知也能实现,没有dispatch_group那么顺手。

tmpuser answered 10 years, 5 months ago

这个真算是月经问题了。我直接放一段代码你就懂了。


 dispatch_group_t serviceGroup = dispatch_group_create();

// Start the first service
dispatch_group_enter(serviceGroup);
[self.configService startWithCompletion:^(ConfigResponse *results, NSError* error){
    // Do something with the results
    configError = error;
    dispatch_group_leave(serviceGroup);
}];

// Start the second service
dispatch_group_enter(serviceGroup);
[self.preferenceService startWithCompletion:^(PreferenceResponse *results, NSError* error){
    // Do something with the results
    preferenceError = error;
    dispatch_group_leave(serviceGroup);
}];

dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
    // Assess any errors
    NSError *overallError = nil;
    if (configError || preferenceError)
    {
        // Either make a new error or assign one of them to the overall error
        overallError = configError ?: preferenceError;
    }
    // Now call the final completion block
    completion(overallError);
});

YANYAN answered 10 years, 5 months ago

Your Answer