剛接觸 iOS 開發半個月,對多執行緒的理解還很淺。今天做了一個簡單需求,順手記錄下來。
網路上看過一篇整理,iOS 平台實作多執行緒可以選擇不同層級的 API:偏底層的 NSThread、中間層的 NSOperationQueue,以及 GCD(Grand Central Dispatch)。今天用的是最直覺的一組:performSelectorInBackground: 與 performSelectorOnMainThread:。
在子執行緒裡做耗時工作(檔案讀寫、上傳等),畫面上顯示一個轉圈的進度指示器;子執行緒完成後通知主執行緒關掉它並刷新 UI。
-(void)listenLogoutStartEvent:(NSNotification *)notification {
UIActivityIndicatorView *indicator =
[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.center = self.view.center;
[self.view addSubview:indicator];
[indicator startAnimating];
[delegate performSelectorInBackground:@selector(doLogout) withObject:nil];
}
performSelectorInBackground: 會開一條新的子執行緒去跑指定方法,因此其中的工作不會阻塞 UI 執行緒,轉圈動畫不會卡住。
-(void)doLogout {
// 檢測網絡
// 備份
[backupDelegate doBackup];
// 向 server 發起註銷請求
// 清除本地登陸數據
[self clearLocalData];
// 通知 MainViewController 註銷完成
[[NSNotificationCenter defaultCenter] postNotificationName:LOGOUT_DONE object:self userInfo:nil];
}
工作完成後廣播一個 LOGOUT_DONE 通知。MainViewController 有監聽這個事件,所以接著會走到它的接收方法。這裡要特別澄清一個常見誤解:通知本身不涉及執行緒切換。就算不用通知、直接呼叫 MainViewController 的方法,執行緒也不會變。用通知的好處是降低元件之間的耦合,而不是切換執行緒。
-(void)listenLogoutDoneEvent:(NSNotification *)notification {
[self performSelectorOnMainThread:@selector(quitApp) withObject:nil waitUntilDone:NO];
// quitApp 中刷新 UI
}
performSelectorOnMainThread: 才是真正把方法排到主執行緒去執行,UI 更新就放在裡面。
performSelectorOnMainThread: 與 performSelectorInBackground: 這對組合可以靈活地在主執行緒與子執行緒之間移動,API 簡單,是很不錯的入門方式。額外提醒:任何 UI 操作都必須在主執行緒進行,這條規則沒有例外。子執行緒只負責運算、IO 與網路,結果一律回主執行緒再套到畫面上。