如何在调用异步API时等待某些操作完成

时间:2013-04-26 11:02:55

标签: ios objective-c macos cocoa

我们有一些操作,但每个操作都会调用Async API。我们希望等到异步API返回然后​​开始执行第二个操作。

Ex:我们有X,Y和Z动作:Method1执行X动作,method2执行Y动作,Method3执行Z动作。这里Method1内部调用一些Async API。所以我们不希望在Method1完成之前调用Method2。

method1 ()

// Here wait till method1 complete 

method2 ()

// Here wait till method12 complete 

method3 () 

method 1 
{
    block{
             // This block will be called by Async API 
          };

   // here invoking Async API
}

可以使用什么来等待方法1完成。 Objective-C的哪种机制更有效? 提前致谢

2 个答案:

答案 0 :(得分:0)

只需在主线程中调用您的方法,因为Async API在后台线程中处理。

答案 1 :(得分:0)

您可以使用dispatch_semaphore_t,在块的末尾发出信号(异步完成块)。此外,如果始终按顺序调用method1,method2,method3,那么他们需要共享信号量,我会将整个事物移动到单个方法。以下是如何完成的示例:

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