蘋果官方文件對 NSNotificationCenter 的描述是:它提供了一種在程式內部「廣播」資訊的機制,本質上就是一張通知分派表(notification dispatch table)。翻成白話:一個物件丟出訊息,任何有興趣的物件都能收到,雙方彼此不必知道對方是誰。
在物件導向的專案裡,A 物件想告訴 B 物件「事情發生了」,常見做法有 delegate、block、KVO,以及這裡的通知中心。通知中心的優勢在於一對多與低耦合——發送方不需要持有接收方的引用,新增一個接收者也不必改動發送方的任何一行程式碼。
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(handleNotification:)
name:@"MyNotificationName"
object:nil];
幾個細節值得留意:
NSNotification *,例如 - (void)handleNotification:(NSNotification *)notification。[[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotificationName"
object:nil
userInfo:@{@"key": @"value"}];
想夾帶資料時,別把自訂物件硬塞進 object,改用 userInfo 字典才是慣例——它天生就是為傳遞附帶資訊而設計的。
addObserver 一定對應 removeObserver。物件銷毀後通知仍送達,就會出現「訊息送給已釋放物件」的經典崩潰。務必在 -dealloc 中收尾:
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
通知中心把「誰知道什麼時候會發生什麼事」這件事,變成鬆散的訊息流。用得好,模組之間乾淨俐落;用得太濫,資料流向會變成一團迷霧。拿捏分寸,比記住 API 更重要。