2012-08-23 52 views
0

這是我的代碼看起來像現在,我想調用以串行方式這些方法:從後臺線程執行的其他方法執行主線程上的方法?

-(void) methodOnBackThread // this method will run on a background thread 
{ 
    [runner runThisMethod]; // and this will run on the same background thread as well 

    [runner runThisOtherMethod]; // and so will this one 

    // but I want this one to run on the main thread :  
    [runner runThisMethodOnTheMainThreadUsing:thisParameter using:thisOtherParamater andUsing:thisOtherOneAsWell]; 

    [runner runThisOtherMethod]; // this one will run on the background thread as well 


    // but I want this one to run on the main thread :  
    [runner runThisMethodOnTheMainThreadUsing:thisParameter using:thisOtherParamater andUsing:thisOtherOneAsWell]; 

    [runner runThisOtherMethod]; // this one will run on the background thread as well 

    // etc.. 

} 

我相信我有使用dispatch_get_main_queue但我無法弄清楚如何實施這個上述情況。

我如何提交[runner runThisMethodOnTheMainThreadUsing:thisParameter using:thisOtherParamater andUsing:thisOtherOneAsWell];主線程,然後返回到我的背景,方法,其餘的執行,然後再拿到主線程如果線下一種方法需要它?

+0

的可能重複[確保功能在主線程上運行僅](http://stackoverflow.com/questions/7852737/make-sure-function-runs-on-main-thread-only) –

回答

3

如果您的目標是iOS4及以上,請使用大中央調度。你可以做這樣的事情:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    //do some stuff here in the background 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     //do some stuff here in the main thread 
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
      //do some stuff here in the background after finishing calling a method on the main thread 
    }); 
    }); 
}); 
1

您可以使用dispatch_get_main_queue像:

dispatch_async(dispatch_get_main_queue(), ^{ 
     if (backgroundTask != UIBackgroundTaskInvalid) 
     { 
      [runner runThisMethodOnTheMainThreadUsing:thisParameter using:thisOtherParamater andUsing:thisOtherOneAsWell]; 
     } 
    }); 

爲了更好地理解有關dispatch檢查這個link

相關問題