在 iOS 開發中,通知(Notification)用於實現界面之間的低耦合傳值,既方便又高效。
设想這樣一個場景:在一個模態彈出的視圖控制器上,還掛著一個可以導航的視圖控制器。這就意味著我們需要把這個導航視圖控制器 naVC.view 添加到模態彈出的視圖控制器 presentedVC.view 之上。
那麼,如何把 naVC 二級視圖控制器上的數據傳給 presentedVC 呢?
解決方案:使用通知。
1、在需要傳值的 naVC 二級視圖控制器中創建一個通知
//創建通知 NSNotification *notification = [NSNotification notificationWithName:@"sendSelectTitle" object:nil userInfo:@{@"key":value}];
2、通過通知中心發送這條通知
//通過通知中心發送通知 [[NSNotificationCenter defaultCenter] postNotification:notification];
3、在需要接收數據的 presentedVC 界面的 viewDidLoad 中,通過通知中心註冊這條通知的觀察者,並綁定要執行的回調方法
//注冊通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(make:)name:@"sendSelectTitle" object:nil];
4、已經註冊過的對象,如果不再需要接收信息,就應該註銷(這段邏輯寫在 presentedVC 模態消失時)
[self dismissViewControllerAnimated:NO completion:^{ // 注銷通知 [[NSNotificationCenter defaultCenter]removeObserver:self name:@"sendSelectTitle" object:nil]; }];
********************系統通知不需要通過通知中心發送************************