2012-06-27 40 views
1

我有一個方法myButtonAction執行一些繁重的計算,我需要在後臺線程上運行,而我正在加載一個視圖,在主線程中指示「任務進度」。只要後臺線程完成執行方法,我需要刪除「任務進度」視圖並在主線程中加載另一個視圖。如何確保線程同步

[self performSelectorInBackground:@selector(myButtonAction) withObject:nil]; 
[self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES]; 

我現在面臨的問題是,myButtonAction完成執行前,LoadView完成其執行。我如何確保LoadView只有在myButtonAction完成執行後纔開始執行。

注:myButtonAction在另一個類中有其方法定義。

回答

2

使用Grand Central Dispatch

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    [self myButtonAction]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self LoadView]; 
    }); 
}); 

或者,如果你想留在performSelector方法:

[self performSelectorInBackground:@selector(loadViewAfterMyButtonAction) withObject:nil]; 

其中

- (void)loadViewAfterMyButtonAction 
{ 
    [self myButtonAction]; 
    [self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES]; 
} 
1

你需要做以下 -

[self performSelectorInBackground:@selector(myButtonAction) withObject:nil]; 

- (void)myButtonAction { 
    //Perform all the background task 

    //Now switch to main thread with all the updated data 
    [self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES]; 
} 

編輯 - 這時可以嘗試 -

[self performSelectorInBackground:@selector(buttonActionInBackground) withObject:nil]; 

- (void)buttonActionInBackground { 
     [self myButtonAction]; 

     //Now switch to main thread with all the updated data 
    [self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES]; 
    } 

現在你不需要改變myButtonAction

+0

myButtonAction'在另一個類中,我不應該編輯它。 –

+0

@XaviValero - 查看編輯過的帖子,如果你想要,也可以去GCD。 – rishi

0

我認爲這個代碼被稱爲在myButtonAction結束:

[self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES]; 

現在難怪的loadView完成myButtonAction完成之前,因爲你說要等到它與做「waitUntilDone:YES」 。在waitUntilDone結束時調用它:NO。

對於這類問題的簡單解決方案,請查看使用[self performSelector:@selector(sel) withObject:obj afterDelay:0.0]或NSTimer將選擇器調用放入主運行循環中 - 例如,如果您想等到UI更新完成。

0

我使用Semaphore Design Pattern這些目的。

+0

這就是我所說的完全過火。如第一個答案中所建議的GCD非常容易地解決了這個問題,對於程序員來說基本上沒有任何努力,並且很少有錯誤的機會。 – gnasher729