如何在asynchronous块内为dispatch_group_async调度dispatch_group_wait

我有这样的代码:

[SVProgressHUD show]; [imageGenerator generateCGImagesAsynchronouslyForTimes:times completionHandler:^(CMTime requestedTime, ...) { dispatch_group_async(queueGroup, queue, ^{ // Do stuff }); }]; dispatch_group_wait(queueGroup, DISPATCH_TIME_FOREVER); [SVProgressHUD dismiss]; 

基本上,显示加载animationHUD,并开始从资产生成图像缩略图,然后一旦隐藏HUD。 我正在使用一个调度组,因为我想确保在隐藏HUD之前生成所有的缩略图。

但是当我运行它时,HUD立即被解雇。 我猜这是因为generateCGImagesAsynchronouslyForTimes: completionHandler:的asynchronous性质generateCGImagesAsynchronouslyForTimes: completionHandler:dispatch_group_wait在completionHandler中的第一个dispatch_group_async之前被调用。

解决这种情况的优雅方法是什么? 谢谢。

把这种方法想象成一个可用于线程的静态计数器,所以当你input一个组时,计数器递增,当该块返回时,递减…

当这个计数器是0时,它会调用一个块来调用

 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 }); 

那是你在想什么?