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

iOS 多線程實作:NSThread、GCD、NSOperation 與背景執行

編輯:iOS 開發綜合

iOS 多線程常見做法包括 NSThread、Grand Central Dispatch、NSOperationQueue 與 performSelectorInBackground。不同方式適合不同情境,理解其特性有助於避免主線程阻塞。

1. NSThread 建立背景執行緒

可使用 detachNewThreadSelector 建立新執行緒:

[NSThread detachNewThreadSelector:@selector(compute:)
                           toTarget:self
                         withObject:[NSNumber numberWithInt:i]];

若要在背景執行後更新主介面,可回到主線程:

[self performSelectorOnMainThread:@selector(updateLabel:)
                         withObject:[NSNumber numberWithDouble:sum]
                      waitUntilDone:NO];

2. GCD 非同步任務

使用全域佇列執行背景任務:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // 背景運算
});

回到主線程更新 UI:

dispatch_async(dispatch_get_main_queue(), ^{
    self.displayLabel.text = @"all done";
});

3. GCD Group 與 Barrier

若需要等待多個任務完成,可使用 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 可用於需要排他執行的情境,例如讀寫共享資料。

4. NSOperationQueue

NSOperationQueue 提供物件導向的操作方式,可搭配 NSInvocationOperation:

NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithInvocation:invocation];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];

5. performSelectorInBackground

若只需要簡單背景執行,可使用:

[self performSelectorInBackground:@selector(compute:)
                       withObject:[NSNumber numberWithInt:i]];

選擇多線程方式時,應優先考慮可讀性、錯誤處理與 UI 更新時機。若任務需要高度並行,GCD 通常較方便;若需要管理任務依賴與取消,NSOperationQueue 更合適。

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