Objective c 等待所有iOS块执行完毕,然后继续
我有一个数据模型/存储对象,它通过几个包含数据的API与Internet接口。要连接的API的数量是动态的:从概念的角度来看,我们可以将端点看作是NSMutabReLay中的字符串。问题是,我想在最后一个端点/API调用完成后通知视图/其他观察者更新的数据。我尝试了GCD调度,但以下模式似乎无法正常工作:Objective c 等待所有iOS块执行完毕,然后继续,objective-c,objective-c-blocks,Objective C,Objective C Blocks,我有一个数据模型/存储对象,它通过几个包含数据的API与Internet接口。要连接的API的数量是动态的:从概念的角度来看,我们可以将端点看作是NSMutabReLay中的字符串。问题是,我想在最后一个端点/API调用完成后通知视图/其他观察者更新的数据。我尝试了GCD调度,但以下模式似乎无法正常工作: dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch
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…]调用中的代码似乎根本就没有执行过?前几天我和调度组一起玩过,这里有一个非常有用的方法,可以帮助您掌握基本知识 但基本上,您似乎错过了进入/离开调度组的线路。因此,您的
runAPI
方法中没有一个正在运行,因为您在组中没有任何项,[[NSNotificationCenter defaultCenter]postNotificationName:@“apiDataUpdated”对象: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];
});
前几天我和调度组一起玩过,这里有一个非常有用的工具,可以帮助你掌握基本知识
但基本上,您似乎错过了进入/离开调度组的线路。因此,您的runAPI
方法中没有一个正在运行,因为您在组中没有任何项,[[NSNotificationCenter defaultCenter]postNotificationName:@“apiDataUpdated”对象: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];
});
谢谢@Rich,让我试试!很抱歉,我混合和匹配了代码,没有从您的问题中删除一些代码,让我用完整的实现编辑答案@UzumakiNaruto:)我想是这样的非常感谢快速回答和代码更新!我想它现在起作用了。谢谢@Rich,让我试试!很抱歉,我混合和匹配了代码,没有从您的问题中删除一些代码,让我用完整的实现编辑答案@UzumakiNaruto:)我想是这样的非常感谢快速回答和代码更新!我想它现在起作用了。