Mulithreading:只有在完成执行其他方法后才执行方法调用

iHS*_*iHS 4 multithreading objective-c grand-central-dispatch ios objective-c-blocks

我试图按照要求异步处理方法,一旦第一个方法完成,只有第二个方法应该开始执行.问题是第一种方法本身具有在后台线程上运行的代码.

我尝试了dispatch_semaphore_wait,但那也没有用.

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);

        dispatch_group_t group = dispatch_group_create();


        dispatch_group_async(group, queue, ^{

            [self firstMethod];
            NSLog(@"firstMethod Done");

        });
        dispatch_group_notify(group, queue, ^ {

            NSLog(@"1st method completed");
            NSLog(@"2nd method starting");

            [self secondMethod];

        });
Run Code Online (Sandbox Code Playgroud)

FirstMethod本身运行在另一个这样的工作线程上

-(void)firstMethod
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
   //processing here.....       

 }];
Run Code Online (Sandbox Code Playgroud)

实现它的最佳方法是什么,我无法更改firstMethod的定义,因为它是由第三方提供的,并且还更改它意味着更改大量现有代码从调用此方法的位置

小智 12

您可以使用完成块.你只需要这样修改firstMethod:

- (void)firstMethodWithOnComplete:(void (^)(void))onComplete {
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
          //processing here.....
          onComplete();
       });
}    
Run Code Online (Sandbox Code Playgroud)

然后以这种方式使用它:

[self firstMethodWithOnComplete:^{
    [self secondMethod];
}];
Run Code Online (Sandbox Code Playgroud)