2012-08-23 51 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

相关问题