2014-01-21 75 views
-2

我需要在啓動應用程序時使用線程在後臺執行一些操作。如何在目標中使用線程c

所以有以下功能,我怎麼能在後臺運行它?

-(void) performOperationInBackground{ 
//Call to other functions 
} 
+7

首先搜索閱讀並學習。比嘗試自己,而不是如果你面臨問題在這裏問。 1. http://www.raywenderlich.com/4295/multithreading-and-grand-central-dispatch-on-ios-for-beginners-tutorial 2.https://developer.apple.com/library/ios/documentation /Cocoa/Conceptual/Multithreading/Introduction/Introduction.html – CRDave

回答

1

,你可以這樣做:

dispatch_async(dispatch_get_main_queue(), ^{ 

    [self performOperationInBackground]; 
}); 

,但請記住,如果該操作後,你想更新UI,你必須在主線程做的,所以後即:

-(void) performOperationInBackground { 

    //do anything in background 

    //call method for update user interface in the Main Thread 
    [self performSelectorOnMainThread:@selector(updateUI) withObject:Nil waitUntilDone:YES]; 

} 

-(void)updateUI { 

    //update user interface 
} 
2

試試這個:

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

冒着被d自己的票投給沒有具體回答這個問題,爲OS X和iOS開發通常使用線程氣餒:

OS X和iOS的採用更異步的方法來執行的併發任務 比傳統的發現基於線程的 系統和應用程序。 應用程序只需要定義特定的任務,然後讓系統 執行它們,而不是直接創建線程。通過讓系統管理線程,應用程序獲得了原始線程無法實現的可伸縮性級別。應用程序 開發人員也可以獲得更簡單和更高效的編程模型。

請參閱Apple的Concurrency Programming Guide

取代線程,您將根據場景使用操作隊列或調度隊列。

但是,您可以這麼做,這與Black Pixel的performSelectorOnMainThread vs. dispatch_async文章中描述的一致性很好。