我不確定您是否在詢問塊的工作方式或如何在主線程上運行完成處理程序。
根據您的代碼,您調用doSomethingInBackground並傳入兩個塊作爲參數。這些塊必須在doSomethingInBackground方法中調用才能運行。 doSomethingInBackground必須是這個樣子:
-(void)doSomethingInBackground:(void (^))block1 completion:(void (^))completion
{
// do whatever you want here
// when you are ready, invoke the block1 code like this
block1();
// when this method is done call the completion handler like this
completion();
}
現在如果你想確保你的完成處理程序在主線程上運行,你會改變你的代碼看起來像這樣:
- (void)doALongTask:(UIView *)someView {
[self doSomethingInBackground:^{
// Runs some method in background, while foreground does some animation.
[self doSomeTasksHere];
} completion:^{
// After the task in background is completed, then run more tasks.
dispatch_async(dispatch_get_main_queue(), ^{
[self doSomeOtherTasksHere];
[someView blahblah];
});
}];
}
這我的回答基於你寫的代碼。但是,如果這個評論「我需要在後臺運行一些任務,那麼在後臺任務完成後,一些任務將在主線程中運行」更能反映你實際正在嘗試做什麼,然後你只是需要這樣做:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// do your background tasks here
[self doSomethingInBackground];
// when that method finishes you can run whatever you need to on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
[self doSomethingInMainThread];
});
});
你的問題是什麼,到底是什麼?如何實現'doSomethingInBackground:completion:'以便在主線程上調用完成處理程序?如果有更多/更簡單的方法來實施......無論「這個」在你的問題中是什麼意思? – danyowdee