2013-04-26 138 views
1

我们有一些操作集,但每个操作都会调用异步API。我们想等到Async API回来,然后开始执行第二个动作。例如:我们有X,Y和Z动作:Method1执行X动作,method2执行Y动作,Method3执行Z动作。这里Method1在内部调用一些Async API。所以我们不想在Method1完成之前调用Method2。如何等待某些操作完成时调用异步API

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的哪种机制更高效? 在此先感谢

+0

您可以使用操作队列为目的的http:// developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationObjects/OperationObjects.html#//apple_ref/doc/uid/TP40008091-CH101-SW1 – Stas 2013-04-26 11:09:32

+0

感谢您的回复,任何其他建议... – Ajay 2013-04-26 11:15:01

+0

你也没有任何干净的代表呢? – 2013-04-26 11:26:16

回答

0

只需在主线程中调用您的方法,因为异步API进程在后台线程中。

0

您可以使用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 
      }); 
     }); 
    }); 
} 
+0

谢谢,我会试试这个 – Ajay 2013-04-29 07:04:46