Grand Central Dispatch.如何运行一个异步组,等待,然后运行另一个,再次等待,然后完成?

ban*_*edo 1 objective-c grand-central-dispatch ios

下面是一个示例函数,我尝试运行一个主要组,等待,然后在不同的线程上运行另外两个后台任务,等待,然后返回在下面显示的常规块中更改的值.下面显示的是我对如何做到这一点的猜测.如果我在一个块中运行这些块,它就可以工作.当我分开块时,它会失败.有没有人有他们如何完成类似的事情的例子?在此先感谢您的帮助.

-(NSString *)sampleFunction:(NSString*)inputString
{
 __block NSString *returnString;

 dispatch_group_t mainGroup = dispatch_group_create();
 dispatch_group_t otherGroup = dispatch_group_create();

 void (^firstBlock)(void) = ^(void)
 {
  ...
 };

 void (^secondBlock)(void) = ^(void)
 {
  ...
 };


 void (^thirdBlock)(void) = ^(void)
 {
  ...
 };

 dispatch_group_async(oneGroup, dispatch_get_global_queue(0, 0), firstBlock);

 dispatch_group_wait(oneGroup, sizeof(int));

 dispatch_group_async(otherGroup, dispatch_get_global_queue(0, 0), secondBlock);
 dispatch_group_async(otherGroup, dispatch_get_global_queue(0, 0), thirdBlock);

 dispatch_group_wait(otherGroup, sizeof(int));

 dispatch_release(userGroup); 
 dispatch_release(otherGroup);

 return returnString;
}
Run Code Online (Sandbox Code Playgroud)

jar*_*jar 7

dispatch_semaphore是你的朋友.:-)

/* Create your semaphore with 0 */
dispatch_semaphore_t sema = dispatch_semaphore_create(0);

/* wait on the semaphore, causes your second & third queue to wait */
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

/* At the end of your first queue finishing, signal the semaphore waiting in 
   the 2nd queue to take over */
dispatch_semaphore_signal(sema);
Run Code Online (Sandbox Code Playgroud)

如果你想要一个更简单的解决方案,只需使用dispatch_apply(它使信号量为你工作)而不是这些组,但不完全确定你正在使用你的组.