多線程主要用來執行耗時工作:下載網路圖片、影片、音樂、書籍,播放遊戲背景音樂等等。把任務分派到多個核心上並行執行,App 才會順。以下整理四種常見技術。
請注意: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]);
}
}
兩種開啟方式:類方法 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,否則容易發生記憶體洩漏。
使用步驟是:建立操作物件(NSInvocationOperation 或 NSBlockOperation),加入 NSOperationQueue,隊列便會自行開啟線程。
@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 是基於 C 的框架,也是 Apple 官方推薦的方案。所有 API 皆以 dispatch 開頭。幾個名詞:global 是全域,queue 是隊列,async 是異步,sync 是同步。
最容易誤解的一點:異步與同步和函式名稱本身無關,而是取決於「在哪個隊列執行」。dispatch_async 不控制先後順序,dispatch_sync 則會等待完成。
可以整理出這樣的規律:在並發隊列(global/concurrent)中,dispatch_sync 與 dispatch_async 依函式名決定同步或異步;而在串行隊列(serial)中,不論後面接的是 sync 還是 async,實際上都會依序執行,且若隊列中的第一個任務是同步的,則整串任務都會在當前線程(一般為主線程)執行,極易造成 deadlock。
這段規律光看文字很難記,強烈建議自己動手寫幾個小測試,把 NSLog 的線程編號印出來,一次就能理解。