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

iOS 多線程四種武器:NSObject、NSThread、NSOperation 與 GCD

編輯:iOS 開發綜合

多線程主要用來執行耗時工作:下載網路圖片、影片、音樂、書籍,播放遊戲背景音樂等等。把任務分派到多個核心上並行執行,App 才會順。以下整理四種常見技術。

一、NSObject 的線程方法

  • performSelectorInBackground:withObject: 開啟後台線程執行指定方法
  • performSelectorOnMainThread:withObject:waitUntilDone: 回到主線程,通常用於更新 UI
  • [NSThread sleepForTimeInterval:] 讓當前線程休眠,多用於模擬耗時以便觀察並行情況

請注意:sleep 只用於測試,上線前務必移除,否則使用者會感受到莫名的延遲。另外,嚴格來說 UI 應在主線程操作,雖然 performSelectorInBackground 中「碰巧」改得動 UI,但這是未定義行為,不該依賴。

- (void)viewDidLoad {
    [super viewDidLoad];

    // 在後台線程執行方法
    [self performSelectorInBackground:@selector(testObject) withObject:nil];

    NSLog(@"main - %@", [NSThread currentThread]);
}

- (void)testObject {
    // 使用 NSThread 或 NSObject 的線程方法時,務必搭配自動釋放池
    @autoreleasepool {
        [NSThread sleepForTimeInterval:2.0f];
        NSLog(@"Background - %@", [NSThread currentThread]);
    }
}

二、NSThread

兩種開啟方式:類方法 detachNewThreadSelector:toTarget:withObject: 一行搞定;或先 initWithTarget:selector:object: 建立實例,再呼叫 start。

- (void)viewDidLoad {
    [super viewDidLoad];

    [NSThread detachNewThreadSelector:@selector(testObject)
                            toTarget:self
                          withObject:nil];

    // 或者:
    // NSThread *thread = [[NSThread alloc] initWithTarget:self
    //                                              selector:@selector(testObject)
    //                                                object:nil];
    // [thread start];

    NSLog(@"main - %@", [NSThread currentThread]);
}

- (void)testObject {
    @autoreleasepool {
        [NSThread sleepForTimeInterval:2.0f];
        NSLog(@"Background - %@", [NSThread currentThread]);
    }
}

同樣地,NSThread 執行的方法內也必須使用 autoreleasepool,否則容易發生記憶體洩漏。

三、NSOperation

使用步驟是:建立操作物件(NSInvocationOperation 或 NSBlockOperation),加入 NSOperationQueue,隊列便會自行開啟線程。

  • 更新 UI 使用 [NSOperationQueue mainQueue]
  • setMaxConcurrentOperationCount 可限制同時並行的線程數,這是 NSOperation 獨有的能力
  • addDependency: 可設定任務的先後順序,甚至跨隊列指定依賴;但切勿循環依賴,否則永遠不會執行
@interface FLViewController ()
{
    NSOperationQueue *_queue;
}
@end

@implementation FLViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 1. 初始化操作隊列
    _queue = [[NSOperationQueue alloc] init];

    // 2. 建立操作
    // NSInvocationOperation *op = [[NSInvocationOperation alloc]
    //     initWithTarget:self selector:@selector(testObject) object:nil];

    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
        [NSThread sleepForTimeInterval:2.0f];
        NSLog(@"Background - %@", [NSThread currentThread]);
    }];

    // 3. 啟動
    [_queue addOperation:op];
}

@end

四、GCD(Grand Central Dispatch)

GCD 是基於 C 的框架,也是 Apple 官方推薦的方案。所有 API 皆以 dispatch 開頭。幾個名詞:global 是全域,queue 是隊列,async 是異步,sync 是同步。

  • 全域隊列:dispatch_get_global_queue,參數為優先級,例如 DISPATCH_QUEUE_PRIORITY_DEFAULT
  • 串行隊列:dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL),需自行建立,無法直接取得
  • 主隊列:dispatch_get_main_queue

最容易誤解的一點:異步與同步和函式名稱本身無關,而是取決於「在哪個隊列執行」。dispatch_async 不控制先後順序,dispatch_sync 則會等待完成。

可以整理出這樣的規律:在並發隊列(global/concurrent)中,dispatch_sync 與 dispatch_async 依函式名決定同步或異步;而在串行隊列(serial)中,不論後面接的是 sync 還是 async,實際上都會依序執行,且若隊列中的第一個任務是同步的,則整串任務都會在當前線程(一般為主線程)執行,極易造成 deadlock。

這段規律光看文字很難記,強烈建議自己動手寫幾個小測試,把 NSLog 的線程編號印出來,一次就能理解。

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