NSNotificationCenter 是 iOS 中常見的一對多訊息通信機制。它允許不同物件之間不必直接持有對方,也能在收到通知時執行指定方法。
通常在初始化時呼叫 addObserver,指定 selector、通知名稱與 object。通知名稱是唯一標識,object 可用來過濾特定發送者。
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(test:)
name:@"test"
object:nil];
需要時可呼叫 postNotificationName,並透過 object 傳遞參數。
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:searchFriendArray];
收到通知後,系統會呼叫註冊的 selector。可從 notification 的 object 取出傳遞的資料。
使用完畢後,記得移除觀察者,避免野指標或重複註冊問題。