2013-10-11 96 views
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下載了,調用completionBlock,然而,startFetch:是異步方法,所以是有任何的方法來確定所有任務,以調用都做completionBlock?如何確定調用異步方法時完成的所有任務?

回答

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); 
     } 
    }]; 
} 
相關問題