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
});
});
});
}