您可以使用 a dispatch_semaphore_t
,您在块(异步完成块)的末尾发出信号。此外,如果方法 1、方法 2、方法 3 总是按顺序调用,那么它们需要共享信号量,我会将整个东西移到单个方法中。这是如何完成的示例:
- (void) method123
{
dispatch_semaphore_t waitSema = dispatch_semaphore_create(0);
callAsynchAPIPart1WithCompletionBlock(^(void) {
// Do your completion then signal the semaphore
dispatch_semaphore_signal(waitSema);
});
// Now we wait until semaphore is signaled.
dispatch_semaphore_wait(waitSema, DISPATCH_TIME_FOREVER);
callAsynchAPIPart2WithCompletionBlock(^(void) {
// Do your completion then signal the semaphore
dispatch_semaphore_signal(waitSema);
});
// Now we wait until semaphore is signaled.
dispatch_semaphore_wait(waitSema, DISPATCH_TIME_FOREVER);
callAsynchAPIPart3WithCompletionBlock(^(void) {
// Do your completion then signal the semaphore
dispatch_semaphore_signal(waitSema);
});
// Now we wait until semaphore is signaled.
dispatch_semaphore_wait(waitSema, DISPATCH_TIME_FOREVER);
dispatch_release(waitSema);
}
或者,您可以通过完成块链接您的调用,如下所示:
- (void) method123
{
callAsynchAPIPart1WithCompletionBlock(^(void) {
// Do completion of method1 then call method2
callAsynchAPIPart2WithCompletionBlock(^(void) {
// Do completion of method2 then call method3
callAsynchAPIPart1WithCompletionBlock(^(void) {
// Do your completion
});
});
});
}