我開始在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.
});
});
我覺得我缺少一些我還不明白的東西。
這個'instanceMethod'做了什麼?顯示其代碼。 – rmaddy
該方法中的代碼很簡單,只是將一個變量填充到用戶默認值。代碼直接使用用戶默認值之後,但並未等待填充。我用日誌替換了代碼並注意到了相同的行爲。問題是爲什麼類實例方法被派發到它自己的線程以及如何確保在完成運行後執行以下代碼。該方法中的代碼與問題無關,因爲任何代碼都會複製該行爲。 – user3473745