我想一个接一个地执行 2 个块,其中每个块都是异步执行的。
例如
[someMethodWithCompletionHandler:^() {
// do something in the completion handler
}];
[anotherMethodWithCompletionHandler:^ {
// do something else in the completion handler after the first method completes
}];
现在,我需要anotherMethodWithCompletionHandler
在 ' ' 完成后发生 ' someMethodWithCompletionHandler
' (包括它的完成处理程序)
通常我会创建一个dispatch_group
并在两个方法之间等待(我不能将这两个方法嵌套在另一个完成处理程序中,因为它需要移动大量代码)
但问题是第一个完成处理程序块是在主线程中调用的(由方法本身在主线程中调用块)所以我不能有效地创建一个dispatch_group
阻塞主线程。
所以线程状态看起来像这样
// 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
}
那么,如果不使用大量嵌套方法并且能够阻塞主线程直到全部完成,我怎么能做到这一点呢?