這是修 bug 時無意間發現的細節,記下來避免再踩。
我在 A 視圖(UITableView)註冊了一個通知,收到通知就重新讀取資料並呼叫 [tableView reloadData]。症狀是:視圖偶爾刷新後顯示的內容不對,切走再切回來又正常了。
// 初始化時註冊通知
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reloadFavDBData:)
name:@"refreshMyFavortieData"
object:nil];
}
// 收到通知後的回呼
- (void)reloadFavDBData:(NSNotification *)sender {
[_dataArray release];
_dataArray = [MusicCollectedDataOperate getSongCollectedInfoWithKeyword:nil];
[tableView reloadData];
}
// 發送者在某個背景執行緒中發出通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshMyFavortieData" object:nil];
在回呼裡打了斷點才發現:它並不在主線程執行。而在這個方法裡我們做了與 UI 相關的 reloadData——在非主線程操作介面,正是顯示異常的原因。
解法很直接:在回呼中切回主線程再做 UI 操作。
- (void)reloadFavDBData:(NSNotification *)sender {
@synchronized(self) { // 保證資料讀寫的執行緒安全
// 先在當前執行緒取資料,因為這步較耗時,
// 若放在主線程反而容易讓 TableView 取值時卡住甚至崩潰
NSArray *tmpArray = [MusicCollectedDataOperate getSongCollectedInfoWithKeyword:nil];
// 切回主線程更新介面
dispatch_async(dispatch_get_main_queue(), ^{
[_dataArray release];
_dataArray = [tmpArray retain];
[tableView reloadData];
});
}
}
這裡刻意把「取資料」與「更新 UI」拆成兩段:前者留在發送通知的執行緒上跑,避免阻塞主線程;後者切回主線程,確保 UIKit 呼叫的安全性。
翻官方文件時,在 NSNotificationCenter 章節看到這段話:
In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself.
意思是:在多執行緒環境下,通知一律在「發送者的執行緒」中被投遞,而不一定是註冊觀察者時所處的那條執行緒。
結論很清楚:通知的回呼方法不會自動幫你切到主線程。只要回呼裡有可能觸碰 UI,就必須自己 dispatch 到主線程,這是一條不能省的規則。