NSNotificationCenter 是蘋果提供給同一程式中「彼此不相識的類」互相溝通的通道。它最大的價值在於解耦:發送方不需要知道誰在聽,接收方也不需要知道是誰發的,雙方只靠一個通知名稱搭上交道橋。使用起來相當方便。
所謂「設定通知」,就是宣告「要在哪個類中接收通知」,通常寫在初始化或 viewDidLoad 中。
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(test:)
name:@"test"
object:nil];
四個參數的意義:
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:searchFriendArray];
postNotificationName 必須與註冊時的 name 完全相同;object 則是用來攜帶參數的載體。
- (void)test:(NSNotification *)notification {
searchFriendArrary = [notification object]; // 取得傳遞的物件
}
若需要傳遞多個值,可以用 NSNotification 的 userInfo 字典,或自訂一個模型物件掛在 object 上。
假設 AppDelegate 負責持有網路連線,收到資料後要通知某個 view controller 更新畫面。由於兩者沒有直接的引用關係,通知中心正好合用。
@implementation chuanzhenAppDelegate
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
// 依收到的內容不同,發送不同的通知;此處發送 Login
[[NSNotificationCenter defaultCenter] postNotificationName:@"Login" object:self];
}
另一邊的 BeforeRootViewController.m 中註冊接收:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(DidLogin)
name:@"Login"
object:nil];
}
- (IBAction)LoginClick {
// 處理登入流程
}
一、記得移除觀察者。NSNotificationCenter 在註冊時會 retain 觀察者,若在 dealloc 之前沒有 removeObserver,一方面觀察者無法被釋放造成洩漏,另一方面若通知在你預期之外的時機送達,selector 會打到已失效的物件而崩潰。傳統寫法是在 dealloc 中呼叫:
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
(iOS 9 之後通知中心改為不強留觀察者,但養成移除的習慣仍是好實務。)
二、通知是同步的。postNotificationName 會立刻、在同一執行緒上把通知依序送給所有觀察者,並等它們全部執行完畢才返回。因此若在主執行緒發送通知,而某個觀察者的 selector 做了耗時運算,整個 UI 就會卡住。這種情況請改用 GCD 把重活丟到背景佇列。
它適合「一對多、且發送方不該認識接收方」的場景,例如鍵盤彈出/收起、使用者登入狀態變更、網路連線狀態切換。若只是父子視圖之間傳值,直接屬性或 delegate 反而更清楚;通知用得太濫,會讓資料流變得難以追蹤,除錯時像在黑暗中摸索。