在 iOS 開發中,多線程常見做法包括 NSThread、NSOperation 與 GCD。其中 NSThread 是最貼近系統線程概念的方式,適合直接用來理解線程建立、啟動、優先級與主線程更新等基礎觀念。
使用 NSThread 時,最基本的方式是透過 initWithTarget:selector:object: 指定要執行的目標物件、方法與參數,再呼叫 start 啟動。
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
thread.threadPriority = 1.0;
thread.name = @"新線程";
[thread start];
threadPriority 可設定在 0.0 到 1.0 之間,用來表達線程優先級;name 則方便除錯時辨識目前是哪一條線程。若要取得當前線程,可以使用 [NSThread currentThread];若要取得主線程,則使用 [NSThread mainThread]。
如果希望某個方法直接在後台執行,可以使用 performSelectorInBackground:withObject:。這種方式很適合執行不想阻塞主線程的任務。
[self performSelectorInBackground:@selector(run3) withObject:nil];
- (void)run3 {
@autoreleasepool {
NSLog(@"主線程:%@,當前線程:%@", [NSThread mainThread], [NSThread currentThread]);
}
}
在後台線程中,建議使用 @autoreleasepool 包裹自動釋放物件,避免記憶體累積。
這是多線程開發最常見的模式:把耗時運算放到子線程,完成後再回到主線程更新畫面。呼叫 performSelectorOnMainThread:withObject:waitUntilDone: 就能把更新動作排回主線程。
- (void)run {
NSLog(@"主線程:%@,當前線程:%@", [NSThread mainThread], [NSThread currentThread]);
[self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:YES];
}
- (void)updateUI {
NSLog(@"在主線程更新 UI");
}
除了直接建立 NSThread,也可以自訂一個子類,並重寫 main 方法。當線程啟動時,系統會自動執行這個 main 方法。
@implementation MyThread
- (void)main {
NSLog(@"子線程 main 方法執行");
}
@end
這種做法適合把特定線程的行為封裝在獨立類別中,讓程式碼結構更清楚,也方便在其他地方重複使用。
NSThread 也提供休眠方法,可用來模擬耗時操作或延遲執行。
[NSThread sleepForTimeInterval:2];
整體來說,NSThread 的 API 直覺易懂,很適合入門多線程。但在實際專案中,仍需注意線程安全、主線程更新限制與資源釋放,才能避免 Race Condition 或畫面卡頓。