等到所有iOS区块执行完毕后再继续 [英] Wait until all iOS blocks are executed before moving on

查看:64
本文介绍了等到所有iOS区块执行完毕后再继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据模型/存储对象,该对象通过几个包含数据的API与Internet交互.接口的API数量是动态的:从概念上讲,我们可以将端点视为NSMutableArray中的字符串.问题是在 last 端点/API调用完成后,我想通知视图/其他观察者更新的数据.我尝试了GCD分派,但以下模式似乎无法正常工作:

I have a data model/store object that interfaces with the Internet over several APIs containing data. The number of APIs to be interfaced with is dynamic: from a conceptual standpoint, we can consider the endpoints to be strings in an NSMutableArray. The issue is that I want to notify views/other observers of updated data after the last endpoint/API call is completed. I tried GCD dispatch but the following pattern doesn't seem to work properly:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, queue, ^{

    for(MyAPIEndpoint __weak __block *ep in apiList)
    {

       [self runAPI:ep withCompletionBlock:^(MyAPIEndpoint *api, NSError *err)
       {
           // update the data model here, code omitted as it's not relevant
       }
       ];
    }
});

dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

// this statement must only execute AFTER the last block in the for loop above is done
[[NSNotificationCenter defaultCenter] postNotificationName:@"apiDataUpdated" object:self];

但是,它似乎不起作用;似乎[self runAPI ...]调用中的代码根本不会执行?

However, it doesn't seem to work; it seems the code inside that [self runAPI...] call is never executed at all?

推荐答案

前几天,我和调度小组一起玩,这对 jrturton 应该可以帮助您了解基础知识!

I played around with dispatch groups the other day, here is a really helpful blog post by jrturton which should help you with the basics!

但是基本上,您似乎缺少进入/离开调度组的行.因此,您的runAPI方法中的任何一个都没有运行,因为您的组中没有项目,并且[[NSNotificationCenter defaultCenter] postNotificationName:@"apiDataUpdated" object:self];被立即调用.

But basically it looks like your missing the line to enter/leave the dispatch group. So non of your runAPI methods are being run as you have no items in the group and [[NSNotificationCenter defaultCenter] postNotificationName:@"apiDataUpdated" object:self]; gets called straight away.

dispatch_group_t group = dispatch_group_create();

for(MyAPIEndpoint __weak __block *ep in apiList)
{
    dispatch_group_enter(group);
    [self runAPI:ep withCompletionBlock:^(MyAPIEndpoint *api, NSError *err)
    {
        // update the data model here, code omitted as it's not relevant
        dispatch_group_leave(group);
    }];
}
});

dispatch_group_notify(group, dispatch_get_main_queue(),^{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"apiDataUpdated" object:self];
});

这篇关于等到所有iOS区块执行完毕后再继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆