NSNotificationCenter 是 iOS 中最容易被低估的工具。它解決的是一個很常見的難題:某件事發生了,我想通知一批「我不認識」的物件。以下從最小可用的三行寫法開始,再談設計上的思考。
// 1. 定義一個要執行的通知方法
- (void)update {
// 收到通知後要做的事
}
// 2. 註冊觀察者,把通知與方法關聯起來
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(update)
name:@"update"
object:nil];
// 3. 在需要發出通知的地方
[[NSNotificationCenter defaultCenter]
postNotificationName:@"update"
object:nil];
三步驟就是全部。但要留意:觀察者必須在 dealloc 中移除註冊,否則物件釋放後通知仍被送達,會造成崩潰。
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
每個執行的 App 都有一個 NSNotificationCenter,功能類似公用布告欄:
許多標準 Cocoa 類別都會主動發送通知:視窗改變大小、選取 table view 的某一列等等,這些都可以在官方文件的「Notifications」章節查到。
聽到「notification center」,很多人會聯想到 IPC(行程間通訊),以為可以「在 A 行程註冊、在 B 行程發送」。這是不行的。NSNotificationCenter 只在同一個行程內溝通。跨行程要嘛用 NSDistributedNotificationCenter(且限於同一台機器),要嘛用分散式物件。
通知物件本身很簡單,只有兩個重要成員:
- (NSString *)name; // 通知的名稱,用來識別 - (id)object; // 通常是發送者本身
另一個是 userInfo,一個 NSDictionary,用來攜帶額外資訊。
命名通知時,慣例是定義一個全域常數,並加上前綴避免與其他元件撞名:
// PreferenceController.h extern NSString * const BNRColorChangedNotification; // PreferenceController.m NSString * const BNRColorChangedNotification = @"BNRColorChanged";
發送時:
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc postNotificationName:BNRColorChangedNotification object:self];
- (id)init {
if (![super init]) return nil;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(handleColorChange:)
name:BNRColorChangedNotification
object:nil];
return self;
}
兩個參數的 nil 各有含義:name 為 nil 代表接收該 poster 發出的所有通知;object 為 nil 代表不限發送者,只要名稱符合就接收。
object 通常是 poster 自己,若要傳更多資訊就用 userInfo:
// poster 端
NSDictionary *d = [NSDictionary dictionaryWithObject:color forKey:@"color"];
[nc postNotificationName:BNRColorChangedNotification
object:self
userInfo:d];
// observer 端
- (void)handleColorChange:(NSNotification *)note {
NSColor *color = [[note userInfo] objectForKey:@"color"];
[tableView setBackgroundColor:color];
}
兩者很像,但差異決定了適用場合:
實務判準:一對一、需要回傳值、雙方關係明確 → 用 delegate;一對多、純通知、發送方不該認識接收方 → 用 NSNotification。例如「使用者改了偏好設定,所有開著的視窗都要更新」就是典型的通知場景。
有個實用的小慣例:Cocoa 若某個標準物件有 delegate 且同時會發通知,它會自動把 delegate 註冊為 observer。而 delegate 方法的命名規則是:把通知名稱去掉 NS 前綴、首字母改小寫、去掉後面的 Notification,再加上冒號。例如要接收 NSWindowDidResizeNotification,就實作:
- (void)windowDidResize:(NSNotification *)aNotification