我有一个数据模型/商店对象,它通过几个包含数据的API与Internet连接。要与之接口的API数量是动态的:从概念的角度来看,我们可以将端点视为NSMutableArray中的字符串。问题是我希望在最后端点/ API调用完成后通知视图/其他观察者更新的数据。我尝试了GCD调度,但以下模式似乎无法正常工作:
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 ...]调用中的代码根本不会被执行?
答案 0 :(得分:4)
前几天我和调度小组一起玩了,blog post这是一个非常有帮助的jrturton,它可以帮助你掌握基础知识!
但基本上看起来你错过了进入/离开调度组的线路。因此,您的runAPI
方法没有被运行,因为组中没有项目,[[NSNotificationCenter defaultCenter] postNotificationName:@"apiDataUpdated" object:self];
会立即被调用。
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];
});