我正在尝试使用 MKNetworkKit 从 Web 服务获取链接数组,然后在后台线程上解析每个响应,并使用 GCD 的 dispatch_group_t 等待所有线程完成处理。我卡住的地方是我无法弄清楚为什么我的 dispatch_group_notify 没有等待组中的所有线程完成。运行此代码将打印:
results count: 0
added into results, count: 1
added into results, count: 2
调度组没有在其线程上等待。我也试过 dispatch_group_wait 但这让我崩溃了。我不知道 MKNetworkKit 对 NSOperation 的使用是否与这个问题相冲突。谢谢你的帮助!
- (MKNetworkOperation *)getABunchOfMovies:(NSArray *)movies onCompletion:(CastResponseBlock)completionBlock onError:(MKNKErrorBlock)errorBlock
{
MKNetworkOperation *operation;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
block NSMutableArray *results = [[NSMutableArray alloc] initWithCapacity:[movies count]];
for (NSString *movieTitle in movies) {
operation = [self operationWithPath:REQUEST_URL(API_KEY, [movieTitle urlEncodedString])];
[operation onCompletion:^(MKNetworkOperation *completedOperation) {
dispatch_group_async(group, queue, ^{
NSDictionary *response = [completedOperation responseJSON];
id result = [self processResponse:response withMovieTitle:movieTitle];
@synchronized (results) {
[results addObject:result];
NSLog(@"added into results, count: %d", [results count]);
}
});
}
onError:^(NSError *error) {
errorBlock(error);
}];
[self enqueueOperation:operation];
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"results count: %d", [results count]);
// Return array here
completionBlock(results);
});
dispatch_release(group);
return operation;
}
编辑:我仍然不知道为什么,但是如果我将其更改为使用 dispatch_group_enter(group); 并将其与 dispatch_group_leave(group) 匹配;在完成块的末尾,它可以工作。有谁知道为什么会这样?