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

iOS 多執行緒入門:performSelectorInBackground 與回主執行緒更新 UI

編輯:iOS 開發綜合

剛接觸 iOS 開發半個月,對多執行緒的理解還很淺。今天做了一個簡單需求,順手記錄下來。

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 的方法,執行緒也不會變。用通知的好處是降低元件之間的耦合,而不是切換執行緒。

回到主執行緒:刷新 UI

-(void)listenLogoutDoneEvent:(NSNotification *)notification {
    [self performSelectorOnMainThread:@selector(quitApp) withObject:nil waitUntilDone:NO];
    // quitApp 中刷新 UI
}

performSelectorOnMainThread: 才是真正把方法排到主執行緒去執行,UI 更新就放在裡面。

小結

  1. 在 iOS 上,performSelectorOnMainThread: 與 performSelectorInBackground: 這對組合可以靈活地在主執行緒與子執行緒之間移動,API 簡單,是很不錯的入門方式。
  2. 更重要的是設計觀念:元件的方法本身不必考慮執行緒,由呼叫者(通常是 view controller)決定它在哪條執行緒上跑。這樣元件保持單純,也能自由複用。

額外提醒:任何 UI 操作都必須在主執行緒進行,這條規則沒有例外。子執行緒只負責運算、IO 與網路,結果一律回主執行緒再套到畫面上。

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