所以,我一直在搜索,但没有找到解决方案,或者至少我无法应用它。 我在stackoverflow上找到this thread,但在我的代码中没有成功实现它。
我的问题是,我需要知道嵌套AFNetworking调用和For循环完成的时间。我曾经和GCD小组一起尝试过,但没有运气。 代码如下所示:
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_async(queue, ^{
[[JSON GET method using AFNetworking 2.0] success:^(NSArray *result) {
dispatch_group_async(group, queue, ^{
//do some work with the result
for (NSDictionary *resultPartDictionary in result) {
dispatch_group_async(group, queue, ^{
//do some more work with parts of the result
[[JSON GET method based on result] success:^(NSArray *result) {
dispatch_group_async(group, queue, ^{
//do some work
for (NSDictionary *resultPartDictionary in result) {
dispatch_group_async(group, queue, ^{
//do some work
[[JSON GET method based on result] success:^(NSArray *result) {
dispatch_group_async(group, queue, ^{
//do some work
for (NSDictionary *resultPartDictionary in result) {
dispatch_group_async(group, queue, ^{
//do some work
});
}
});
}];
});
}
});
}];
});
}
});
}
});
}
现在,一切正常。我在块中处理核心数据,所以我需要每个线程都有MOC,这也适用。
我唯一想知道的是如何知道所有这些块何时完成。 谢谢!
修改
所以,我已尝试使用dispatch_group_enter(group)
和dispatch_group_leave(group)
,但在我看来,这种嵌入式架构无法实现。由于For循环,"离开"通知太多,导致异常或不足,dispatch_group_notify
返回得太早。
关于这个的任何想法?
答案 0 :(得分:5)
您正在寻找dispatch_group_notify
和dispatch_group_enter
/ dispatch_group_leave
。
dispatch_group_notify
执行给定队列中的给定块。dispatch_group_enter
增加了组中执行任务的当前计数。必须通过调用dispatch_group_enter
来平衡每个dispatch_group_leave
。dispatch_group_leave
减少了组中执行任务的当前计数。 因此,在网络调用开始之前,您应该通过增加组中任务的数量来欺骗dispatch_group_notify
,并在完成所有操作后减少它。要实现此目的,请在dispatch_group_enter
之前致电dispatch_async
,然后在最后一个主题中调用dispatch_group_leave
。由于您知道每个结果数组的元素计数,因此可以检查当前线程是否是最后一个。
dispatch_group_enter(group); // Increases the number of blocks in the group.
dispatch_async(queue, ^{
// Make your AFNetworking calls.
dispatch_group_async(group, queue, ^{
//do some work.
if (isLastThread)
dispatch_group_leave(group); // Decreases the number of blocks in the group.
});
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{ // Calls the given block when all blocks are finished in the group.
// All blocks finished, do whatever you like.
});