多執行緒是 iOS 開發中提升效能與使用者體驗的關鍵。本文從單例寫法、三種 NSThread 開啟方式,一路整理到 NSOperation 與 GCD 的核心概念。
+ (SingleHandel *)shareModel {
static dispatch_once_t onceQueue;
dispatch_once(&onceQueue, ^{
shareSingle = [[SingleHandel alloc] init];
});
return shareSingle;
}
// 第一種:透過 NSThread 建立 NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(threadAction) object:nil]; thread1.name = @"thread1"; // 為執行緒命名 [thread1 start]; // 啟動 [thread1 cancel]; // 取消 // 第二種:程序執行時自動開啟 [NSThread detachNewThreadSelector:@selector(threadAction) toTarget:self withObject:nil]; // 第三種:在背景執行 [self performSelectorInBackground:@selector(threadAction) withObject:nil];
NSInvocationOperation *inOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocation) object:nil];
NSBlockOperation *blockOp = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"我是 block");
}];
// 建立佇列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 設定最大同時執行數量
queue.maxConcurrentOperationCount = 1;
// 加入工作
[queue addOperation:inOp];
[queue addOperation:blockOp];
GCD 遵循先進先出(FIFO)原則,分為三種佇列:
基本派發寫法:
dispatch_queue_t myQueue = dispatch_queue_create("com.myqueue", DISPATCH_QUEUE_SERIAL);
dispatch_async(myQueue, ^{
NSLog(@"第一個任務 %@", [NSThread currentThread]);
});
// 延遲 4 秒執行
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self afther];
});
// 重複執行 3 次
dispatch_apply(3, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t t) {
[self afther];
});
// 只執行一次
static dispatch_once_t onceQueue;
dispatch_once(&onceQueue, ^{
NSLog(@"我就執行一次");
});
子執行緒完成工作後,常需要回到主執行緒更新 UI。透過 detachNewThreadSelector 開啟子執行緒,並在方法內呼叫 performSelectorOnMainThread 即可跳回主執行緒:
- (void)newThread {
NSLog(@"我是子執行緒");
// 回到主執行緒
[self performSelectorOnMainThread:@selector(afther) withObject:self waitUntilDone:NO];
}
掌握 NSThread、NSOperation 與 GCD 這三套工具,就能依場景選擇最合適的併發方案,讓 App 在保持流暢的同時充分利用多核心效能。