MKNetworkKit和GCD dispatch_group_t

时间:2012-08-08 06:03:22

标签: objective-c ios objective-c-blocks grand-central-dispatch mknetworkkit

我正在尝试使用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)匹配;在完成块结束时,它工作。有谁知道为什么会这样?

1 个答案:

答案 0 :(得分:2)

目前,MKNetworkKit不支持队列完成处理程序。 你应该考虑添加操作依赖而不是这个hack。

[lastOperation addDependency:op1];
[lastOperation addDependency:op2];

并假设当“lastOperation”完成时,队列确实已完成。

另一种方法是KVO引擎上的“operationCount”键路径并检查它是否达到零。

MKNetworkEngine有一个代码块,用于显示和隐藏网络活动指示符。