Ios 如何等待所有异步任务?

Ios 如何等待所有异步任务?,ios,afnetworking,grand-central-dispatch,Ios,Afnetworking,Grand Central Dispatch,我异步下载某个对象,并将其存储在数组中。接下来,对于每个对象,我使用地理编码(也是异步的)下载一些坐标,并使用新参数(坐标)更新每个对象的数据库。我的方法如下所示: - (void)downloadObjectsWithTitle:(NSString *)title andHandler:(void(^)(NSMutableDictionary *result))handler { AFHTTPClient *httpClient = [[AFHTTPClient alloc] init

我异步下载某个对象,并将其存储在数组中。接下来,对于每个对象,我使用地理编码(也是异步的)下载一些坐标,并使用新参数(坐标)更新每个对象的数据库。我的方法如下所示:

- (void)downloadObjectsWithTitle:(NSString *)title andHandler:(void(^)(NSMutableDictionary *result))handler {
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET"
                                                        path:nil
                                                  parameters:nil];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        //I get here array of objects
        //now for each object I want to download geocoding localization so i called another asynchronyous method getLocationWithTitle:andHandler;
       for(int i = 0; i < resutArray.count; i++) {
           [self downloadLocationWithString:[dictionary objectForKey:@"string"] andHandler:^(NSMutableDictionary *result) {
               //update database;
           }];
        }
        handler(dictionary);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [operation start];
}
所以,在退出方法(FireHandler)之前,等待每个坐标的下载(对于每个对象)


THNAK用于所有建议。

尝试使用全局标志。先定不。在下载块中,下载完成后,将成套标志设置为“是”。你可以检查那个标志

假设您在并发队列上使用
downloadLocationWithString:
中的
dispatch\u async

dispatch_barrier_async(queue, ^{
    // will only be called after all the blocks submitted to queue have finished.
}];

(如果您使用的是串行队列,只需在最后一个块的最后一行调用处理程序即可)

维护所有任务的计数。当它为零时,您就完成了。

如果我只有一个请求地理编码,那么这个解决方案就可以了。但对于多个,它不起作用。获取全局变量,并根据下载完成时的下载总数分配它,只要将变量减少1即可。您可以检查该变量的值,如果其为0,则所有ur下载都已完成。
dispatch_barrier_async(queue, ^{
    // will only be called after all the blocks submitted to queue have finished.
}];