您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 多執行緒完全指南:NSThread、NSOperation 與 GCD

編輯:iOS 開發綜合

多執行緒是 iOS 開發中提升效能與使用者體驗的關鍵。本文從單例寫法、三種 NSThread 開啟方式,一路整理到 NSOperation 與 GCD 的核心概念。

單例模式

+ (SingleHandel *)shareModel {
    static dispatch_once_t onceQueue;
    dispatch_once(&onceQueue, ^{
        shareSingle = [[SingleHandel alloc] init];
    });
    return shareSingle;
}

NSThread 的三種開啟方式

// 第一種:透過 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];

NSOperation 與 NSOperationQueue

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:三大佇列類型

GCD 遵循先進先出(FIFO)原則,分為三種佇列:

  • 主佇列(串行):使用 dispatch_get_main_queue(),任務在主執行緒依序執行。
  • 自訂佇列(串行):以 DISPATCH_QUEUE_SERIAL 建立,前一個任務完成後下一個才執行。
  • 自訂佇列(並行):以 DISPATCH_QUEUE_CONCURRENT 建立,任務可同時執行。
  • 全域佇列(並行):以 dispatch_get_global_queue 取得,任務並行處理。

基本派發寫法:

dispatch_queue_t myQueue = dispatch_queue_create("com.myqueue", DISPATCH_QUEUE_SERIAL);
dispatch_async(myQueue, ^{
    NSLog(@"第一個任務 %@", [NSThread currentThread]);
});

GCD 的延遲、重複與單次執行

// 延遲 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 在保持流暢的同時充分利用多核心效能。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved