想在 A 類別裡觸發 B 類別的方法,通知(notification)是一種低耦合的做法:發送者不需要知道誰在聽,也不需要持有對方的參照。
NSNotification *notification = [NSNotification notificationWithName:kImageNotificationLoadFailed
object:self
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
error, @"error",
connection.imageURL, @"imageURL", nil]];
實務上,建立自己的 NSNotification 物件並非必要。多數情況直接用 NSNotificationCenter 的 postNotificationName:object: 或 postNotificationName:object:userInfo: 發送通知更簡便。
每個 App 都有一個自己的通知中心,它採用單例設計,透過 defaultCenter 取得唯一物件。
另外要注意:NSNotification 是不可變物件,一旦建立就無法修改內容。
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(aWindowBecameMain:)
name:NSWindowDidBecomeMainNotification
object:nil];
addObserver:selector:name:object: 除了指定觀察者,還指定了收到通知後要呼叫的方法。為了防禦式設計,最好先確認對方真的實作了該方法:
if ([observer respondsToSelector:@selector(aWindowBecameMain:)]) {
[[NSNotificationCenter defaultCenter] addObserver:observer
selector:@selector(aWindowBecameMain:)
name:NSWindowDidBecomeMainNotification
object:nil];
}
[[NSNotificationCenter defaultCenter]
postNotificationName:@"ConverterAdded" object:self];
[[NSNotificationCenter defaultCenter]
postNotificationName:@"ConverterRemoved" object:self];
舉個例子:一個 App 支援把文件做各種格式轉換,每個轉換器由獨立的 Converter 物件處理。當使用者安裝或移除某個轉換器時,App 只需要發出 ConverterAdded 或 ConverterRemoved 通知即可,完全不需要知道有哪些物件正在關注這件事。這就是通知機制最大的價值。
如果需要傳遞額外資料,用 userInfo 字典:
[[NSNotificationCenter defaultCenter]
postNotificationName:@"ConverterAdded"
object:self
userInfo:@{@"converterName": @"RTF2ASCII"}];
若要在主執行緒發送:
[[NSNotificationCenter defaultCenter]
performSelectorOnMainThread:@selector(postNotification:)
withObject:notification
waitUntilDone:YES];
// 移除該觀察者的所有註冊
[[NSNotificationCenter defaultCenter] removeObserver:observer];
// 只移除符合條件的單一註冊
[[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];
removeObserver: 會刪除通知中心調度表中屬於該觀察者的所有項目,而 removeObserver:name:object: 只刪除符合條件的項目。傳入的 observer 不能為 nil,否則行為未定義。
在現代 iOS(9 之後)中,以 block 或 selector 註冊的觀察者會被通知中心自動持有並在釋放時移除,但如果你用 block 形式註冊,仍然建議保存回傳的 token 並在 dealloc 中明確 removeObserver:,這是較安全的習慣。
通知中心內部維護一份調度表,是某些觀察者感興趣的通知集合。每個項目包含三個部分:觀察者(必須)、通知名稱、通知發送者。