0

I want to perform 2 blocks one after the other , where each on there own are performed asynchronously.

For instance

[someMethodWithCompletionHandler:^() {
  // do something in the completion handler
}];

[anotherMethodWithCompletionHandler:^ {
  // do something else in the completion handler after the first method completes
}];

Now, I need 'anotherMethodWithCompletionHandler' to happen after 'someMethodWithCompletionHandler' completes (including its completion handler)

regularly I would create a dispatch_group and wait in between the 2 methods (I can not nest the 2 methods in the other completion handler because it would require a lot of code to be moved)

But the problem is that the first completion handler block is called in the main thread (by the method itself calling the block in the main thread) so I can not effectively create a dispatch_group blocking the main thread.

So the thread state looks something like this

// main thread here

[self doFirstPortionOfWork];

// main thread here
[self doSecondPortionOfWork];


-(void)doFirstPortionOfWork
{
.. a lot of stuff happening
  [someMethodWithCompletionHandler:^{
  // this is the main thread
  }];
// would like to block the return here until the completion handler finishes
}

-(void)doSecondPortionOfWork
{
... a lot of work here
  [anotherMethodWithCompletionHandler^{
  // this is also called into the main thread
  }];
// would like to block the return here until the completion handler finishes
}

So how could I do this with out resorting to a lot of nested methods and be able to block the main thread until all complete?

Avba
  • 14,822
  • 20
  • 92
  • 192

1 Answers1

1

Main Thread is the same as Main Queue

It is not possible to wait on Main Thread for future work in Main Thread. You are blocking the future work.

You can do it like this:

[someMethodWithCompletionHandler:^() {
    // do something in the completion handler
    [anotherMethodWithCompletionHandler:^ {
       // do something else in the completion handler after the first method completes
    }];
}];
Tricertops
  • 8,492
  • 1
  • 39
  • 41