2012-10-26 30 views
1

我在iPad上有一個功能,我需要依次運行3個步驟,比如說task1,task2,task3。 Task2需要從服務器加載一些數據。所以我需要把task2放到一個單獨的後臺線程中。如何向Xcode的主線程發送消息或通知?

- (IBAction)dbSizeButton:(id)sender { 

    //Task1...... 

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 

    dispatch_async(queue, ^{ 

     //Task2 .....which go to server and download some stuff and update database. 

     dispatch_sync(dispatch_get_main_queue(), ^{ 
      //Task3, continue to work on UI 
     }); 
    }); 
} 

但是看起來發生了什麼是應用程序在Task2啓動時經常被殺死。我不確定爲什麼。我可以看到Task2在單獨的線程中執行。所以我想知道,如果不是這樣做,而不是使用GCD,我可以在Task2結束時向主線程發送消息或通知,以便啓動Task3?如何做到這一點?

回答

2

要使用NSOperation和NSOperationQueue代替GCD,您想要實現的目標會更容易。它不會觸發通知,但我相信它可以做你想做的事情。

如果我正確理解您的問題,您當前正在主線程中運行task1。後來Task2通過task1同時觸發,但task2告訴task3調用UI。換句話說,任務2和任務3 取決於任務1上的,對吧?

使用NSOperations(操作是一段代碼,可以在不同的線程中運行選擇器或塊)和NSOperationQueues,您可以在一分鐘內實現這些依賴關係。

//Assuming task1 is currently running. 
NSOperationQueue *downloadAndUpdate; //Leaving out initialization details. 

NSOperationBlock *task2; //Leavign out initialization details. 
NSOperationBlock *task3; 

//This is where it gets interesting. This will make sure task3 ONLY gets fired if task2 is finished executing. 
[task3 addDependency:task2]; 

//Task3 could have the following code to update the main thread. 

[[NSOperationQueue mainQueue] addOperation:myUIUpdatingTask]; 

這些API的級別高於GCD,我絕對推薦您學習如何使用它們來創建更好的併發性。

Here's a tutorial爲了幫助您開始使用這些API。我寫這篇教程是因爲我需要一種比GCD更好的併發性方式,並最終學習了這一點。我喜歡教我學什麼)。

+0

這非常有趣。我會明天嘗試一下,看看它是否適合我。非常感謝。 – user518138

5

問題只是你使用dispatch_sync,這個塊。這就是你被殺的原因。你幾乎沒有錯。你想要的是:

// ... task 1 on main thread 
dispatch_async(other_queue, ^{ 
    // ... task 2 in background thread 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     // ... task 3 on main thread 
    }); 
}); 

這是下線主線程和回來的標準模式。這裏的所有都是它的!

相關問題