首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

iOS NSNotificationCenter 通知機制實戰:廣播、傳值與記憶體管理

     編輯:C++ 入門

通知機制簡介

NSNotificationCenter 實現 觀察者模式:發送者廣播通知,註冊的觀察者接收並響應。適用於「一對多」、「跨層級」、「非強耦合」的消息傳遞。

基本用法三步驟

  1. 註冊觀察者:
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle:) name:@"MyNotification" object:nil];
  2. 發送通知:
    [[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self userInfo:@{@"key": @value}];
  3. 移除觀察者(必須,防野指針):
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"MyNotification" object:nil];
    通常在 dealloc 或 viewDidDisappear 中調用。

完整 Demo:三頁面背景色聯動

場景:第 2 頁 UITextField 開始編輯 → 廣播通知 → 第 1、3 頁背景變紅。

第 2 頁:發送通知

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    NSLog(@"開始編輯");
    // 簡單廣播
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeColor" object:self];
    // 或攜帶數據
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeColor"
                                                        object:self
                                                      userInfo:@{@"color": @"red"}];
}

第 1/3 頁:註冊與響應

- (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 會收到多次回調,務必配對移除。
  • iOS 9+:若觀察者為 UIViewController,系統在 dealloc 自動移除,但**不依賴此行為**,顯式移除更安全。

最佳實踐

  1. 通知名稱用 static NSString *const 定義常量,避免拼寫錯誤。
  2. object 參數可傳 self 以便接收端識別發送者,或傳 nil 表示不限發送者。
  3. 高頻通知考慮用 NSNotificationQueue 合併延遲投遞。
  4. 嚴格配對 addObserver / removeObserver,寫在 dealloc 最保險。

總結

NSNotificationCenter 是 iOS 輕量級解耦利器。掌握「註冊→發送→移除」閉環、userInfo 傳值、記憶體管理鐵律,即可在多控制器、跨層級場景下優雅傳遞消息。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved