2014-03-28 47 views
-2

我開始在iOS和Objective C編程中遇到一個問題,我的代碼沒有同步執行。方法正在另一個線程中運行。

以下代碼在我的ViewController.m文件中。

[[self classInstance] instanceMethod]; 
//more code here executes at the same time as instanceMethod 

我instanceMethod和代碼後在同一時間執行,但該代碼後依靠instanceMethod運行。最初我試圖把它放在一個單獨的線程中,然後在它完成後運行代碼,但似乎不管什麼instanceMethod永遠都不會等待。

我已經能夠得到它的工作的唯一辦法是通過做:

[[self classInstance] instanceMethod]; 
while(self.classInstance.instanceVariable == nil){ 
    // wait for other code to fill the variables I need 
    // do nothing 
} 
// execute remaining code 

下面我試過,但預期它不工作。

dispatch_async(backgroundQueue, ^{ 
    [[self classInstance] instanceMethod]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     //other code here for once instanceMethod is completed. 
    });  
}); 

我覺得我缺少一些我還不明白的東西。

+3

這個'instanceMethod'做了什麼?顯示其代碼。 – rmaddy

+0

該方法中的代碼很簡單,只是將一個變量填充到用戶默認值。代碼直接使用用戶默認值之後,但並未等待填充。我用日誌替換了代碼並注意到了相同的行爲。問題是爲什麼類實例方法被派發到它自己的線程以及如何確保在完成運行後執行以下代碼。該方法中的代碼與問題無關,因爲任何代碼都會複製該行爲。 – user3473745

回答

1

這是一個很好的解決方案,以完成塊添加到instanceMethod

[[self classInstance] instanceMethodWithCompletion:^{ 
    // Handle finish of the instance method 
}]; 

,並宣佈instanceMethod這樣的:

- (void)instanceMethodWithCompletion:(void (^)(void))completion { 
    // Do something... 

    if(completion) { 
     completion(); 
    } 
} 

它將使instanceMethod告訴它已經完成並運行塊內的任何其他代碼。

+0

謝謝,這個作品完美。任何想法,爲什麼如果我創建一個線程,並派遣兩個塊dispatch_sync,他們不按順序執行該線程?或者你也許知道一個資源來演示究竟發生了什麼? – user3473745

+0

我猜'instanceMethod'啓動了一些異步操作,不是嗎?這可能是這個問題的一個原因。 –

+0

爲了更準確地回答你的問題,我需要看看'instanceMethod'的作用。 –

相關問題