2013-04-26 136 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