在ios開發過程當中,常常會遇到在服務器端獲取完數據經過後臺使用多線程方式自動更新UI,一般的作法有兩種:ios
一、使用NSObject類的方法performSelectorInBackground:withObject:來建立一個線程。服務器
具體的代碼:多線程
[Object performSelectorInBackground:@selector(doSomething:) withObject:nil];函數
二、選擇使用NSThread實現多線程。spa
NSThread建立主要有兩種方式:線程
(1):code
[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];orm
(2):內存
NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:nil];ci
[myThread start];
這兩種方式的區別在於:
前一種調用就會當即建立一個線程並執行selector方法;第二種方式儘管alloc了一個新Thread,但須要手動調用start方法來啓動線程。這點與Java建立線程的方式類似。
第一種方式,與上述作法1使用NSObject的類方法performSelectorInBackground:withObject:是同樣的;第二種方式的能夠在start真正建立線程以前對其進行設置,好比設置線程的優先級。
注意:
- (void) doSomething:(id)sender
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//執行你的代碼
[pool release];
}
在多線程的執行方法doSomething中須要自行管理內存的釋放,不然可能會警告提示:
XXXXX nsthread autoreleased with no pool in place – just leaking
補充:若是要更新UI必須回到主線程中,能夠用performSelectorOnMainThread回到主線程(更新UI的話必須到主線程),用或者調用或者調用 委託函數,在主線程中實現委託函數