如何确定调用异步方法时完成的所有任务?

时间:2013-10-11 02:24:12

标签: ios objective-c

- (void)downloadUrls:(NSArray *)urls completionBlock:(void(^)(NSArray *results))completionBlock {
    NSMutableArray *results = [NSMutableArray array];
    BOOL finishAll = NO;
    for(NSString *url in urls) {
        [Downloader startFetch:url completion:^(id response){
            [results addObject:response];
        }];
    }
    if(finishAll){
        completionBlock(results);
    }
}

我需要使用此方法下载许多网址,如果所有网址都已下载,请调用completionBlock,startFetch:是异步方法,那么有没有办法确定所有任务已按顺序完成调用completionBlock?

1 个答案:

答案 0 :(得分:2)

不在downloadURLs:completionBlock:内,不,但您可以检查您是否在startFetch:completion:完成区内的最后一项。

[Downloader startFetch:url completion:^(id response){
        [results addObject:response];
        if( [results count] == [urls count] ){
            completionBlock(results);
        }
}];

NSMutableArray *results = [NSMutableArray array];
id lastURL = [results lastObject];
for(NSString *url in urls) {
    [Downloader startFetch:url completion:^(id response){
        [results addObject:response];
        if( url == lastURL ){
            completionBlock(results);
        }
    }];
}