我的代码看起来像这样:
[SVProgressHUD show];
[imageGenerator generateCGImagesAsynchronouslyForTimes:times
completionHandler:^(CMTime requestedTime, ...) {
dispatch_group_async(queueGroup, queue, ^{
// Do stuff
});
}];
dispatch_group_wait(queueGroup, DISPATCH_TIME_FOREVER);
[SVProgressHUD dismiss];
基本上,显示加载动画 HUD 并开始从 Assets 生成图像缩略图,然后在完成后隐藏 HUD。我正在使用调度组,因为我想确保在隐藏 HUD 之前生成所有缩略图。
但是当我运行它时,HUD 会立即消失。我猜这是因为 generateCGImagesAsynchronouslyForTimes: completionHandler:
--dispatch_group_wait
的异步性质在 completionHandler 中的第一个 dispatch_group_async
之前被调用.
解决这种情况的优雅方法是什么?谢谢。
最佳答案
将此方法视为线程可用的静态计数器,因此当您进入一个组时,计数器递增,而当该 block 返回时,递减...
当那个计数器为0时,它会调用一个 block 来调用
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
while(someCondition)
{
dispatch_group_enter(group);
[SomeClassThatLoadsOffTheInternet getMyImages:^{
// do something with these.
dispatch_group_leave(group);
});
}
dispatch_group_notify(group, queue, ^{
// do something when all images have loaded
});
这是你的想法吗?
关于ios - 如何在异步 block 内为 dispatch_group_async dispatch_group_wait,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20133770/