0

我想一个接一个地执行 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
}

那么,如果不使用大量嵌套方法并且能够阻塞主线程直到全部完成,我怎么能做到这一点呢?

4

1 回答 1

1

主线程与主队列相同

不可能在主线程上等待主线程中的未来工作。你正在阻止未来的工作。

你可以这样做:

[someMethodWithCompletionHandler:^() {
    // do something in the completion handler
    [anotherMethodWithCompletionHandler:^ {
       // do something else in the completion handler after the first method completes
    }];
}];
于 2014-06-27T17:39:49.463 回答