0
- (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);
    }
}

我需要用这个方法下载很多url,如果所有的url都下载了,调用completionBlock,但是,这startFetch:是一个异步方法,那么有没有办法确定所有任务都完成了,以便调用completionBlock?

4

1 回答 1

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);
        }
    }];
}
于 2013-10-11T02:47:05.857 回答