gpt4 book ai didi

ios - 等待嵌套的 AFNetworking 调用和循环完成

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:22:01 24 4
gpt4 key购买 nike

所以,我一直在寻找解决方案,但没有找到解决方案,或者至少我无法应用它。我找到了 this thread在 stackoverflow 上,但没有在我的代码中成功实现它。

我的问题是,我需要知道嵌套的 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
});
}
});
}];
});
}
});
}];
});
}
});
}
});
}

现在,一切正常。我在 block 内处理核心数据,所以我需要每个线程的 MOC,这也能正常工作。

我唯一想知道的是如何知道所有这些 block 何时完成。谢谢!

编辑

所以,我已经尝试使用 dispatch_group_enter(group)dispatch_group_leave(group),但在我看来,这种嵌入式架构是不可能的。由于 For 循环,“离开”通知要么太多,导致异常,要么不够,dispatch_group_notify 返回得太早。对此有什么想法吗?

最佳答案

您正在寻找 dispatch_group_notifydispatch_group_enter/dispatch_group_leave

  • dispatch_group_notify 执行给定队列中的给定 block ,当组中的每个 block 都完成时。
  • dispatch_group_enter 增加组中当前执行任务的计数。每个 dispatch_group_enter 都必须与对 dispatch_group_leave 的调用保持平衡。
  • dispatch_group_leave 减少组中执行任务的当前计数。

因此,您应该欺骗 dispatch_group_notify,在网络调用开始之前增加组中任务的数量,并在一切结束时 reduce task 数量。为此,请在 dispatch_async 之前调用 dispatch_group_enter 并在最后一个线程中调用 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.
});

关于ios - 等待嵌套的 AFNetworking 调用和循环完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23788585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com