iOS 多線程常見做法包括 NSThread、Grand Central Dispatch、NSOperationQueue 與 performSelectorInBackground。不同方式適合不同情境,理解其特性有助於避免主線程阻塞。
可使用 detachNewThreadSelector 建立新執行緒:
[NSThread detachNewThreadSelector:@selector(compute:)
toTarget:self
withObject:[NSNumber numberWithInt:i]];
若要在背景執行後更新主介面,可回到主線程:
[self performSelectorOnMainThread:@selector(updateLabel:)
withObject:[NSNumber numberWithDouble:sum]
waitUntilDone:NO];
使用全域佇列執行背景任務:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 背景運算
});
回到主線程更新 UI:
dispatch_async(dispatch_get_main_queue(), ^{
self.displayLabel.text = @"all done";
});
若需要等待多個任務完成,可使用 dispatch_group:
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
// 任務一
});
dispatch_group_async(group, queue, ^{
// 任務二
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// 全部完成
});
dispatch_barrier_async 可用於需要排他執行的情境,例如讀寫共享資料。
NSOperationQueue 提供物件導向的操作方式,可搭配 NSInvocationOperation:
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithInvocation:invocation];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];
若只需要簡單背景執行,可使用:
[self performSelectorInBackground:@selector(compute:)
withObject:[NSNumber numberWithInt:i]];
選擇多線程方式時,應優先考慮可讀性、錯誤處理與 UI 更新時機。若任務需要高度並行,GCD 通常較方便;若需要管理任務依賴與取消,NSOperationQueue 更合適。