NSNotificationCenter 實現 觀察者模式:發送者廣播通知,註冊的觀察者接收並響應。適用於「一對多」、「跨層級」、「非強耦合」的消息傳遞。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle:) name:@"MyNotification" object:nil];[[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self userInfo:@{@"key": @value}];[[NSNotificationCenter defaultCenter] removeObserver:self name:@"MyNotification" object:nil];dealloc 或 viewDidDisappear 中調用。場景:第 2 頁 UITextField 開始編輯 → 廣播通知 → 第 1、3 頁背景變紅。
- (void)textFieldDidBeginEditing:(UITextField *)textField {
NSLog(@"開始編輯");
// 簡單廣播
[[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeColor" object:self];
// 或攜帶數據
[[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeColor"
object:self
userInfo:@{@"color": @"red"}];
}
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(changeColor:)
name:@"ChangeColor"
object:nil];
}
- (void)changeColor:(NSNotification *)note {
// 無數據版本
self.view.backgroundColor = [UIColor redColor];
// 有數據版本
NSDictionary *info = note.userInfo;
NSString *color = info[@"color"];
if ([color isEqualToString:@"red"])
self.view.backgroundColor = [UIColor redColor];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"ChangeColor" object:nil];
}
userInfo 為 NSDictionary,可攜帶任意鍵值對。接收端從 note.userInfo 取值,建議做類型檢查。
EXC_BAD_ACCESS。addObserver 會收到多次回調,務必配對移除。UIViewController,系統在 dealloc 自動移除,但**不依賴此行為**,顯式移除更安全。static NSString *const 定義常量,避免拼寫錯誤。object 參數可傳 self 以便接收端識別發送者,或傳 nil 表示不限發送者。NSNotificationQueue 合併延遲投遞。addObserver / removeObserver,寫在 dealloc 最保險。NSNotificationCenter 是 iOS 輕量級解耦利器。掌握「註冊→發送→移除」閉環、userInfo 傳值、記憶體管理鐵律,即可在多控制器、跨層級場景下優雅傳遞消息。