通知中心,它是IOS程序內部的一種消息廣播機制,通過它,可以實現無引用關系的對象之間的通信。通知中心他是基于觀察者模式,它只能進行程序內部通信,不能跨應用程序進程通信。當通知中心接受到消息后會根據設置,將消息發送給訂閱者,這里的訂閱者可以有多個。
通知中心與代理模式類似,都可以實現多個對象間通信,通知中心可以將一個通知發送給多個監聽者,而代理模式每個對象只能添加一個代理。但無論是那種模式,都是一種低耦合的設計,實現對象間的通信。
1、注冊觀察者對某個事件(以字符串命名)感興趣,并設置該事件觸發時執行的Selector或Block
2、NSNotificationCenter在某個時機激發事件(以字符串命名)
3、觀察者在收到感興趣的事件時,執行相應地Selector或Block
4、移除通知
利用導航添加三個界面,在第三個界面上添加一組按鈕,當點擊按鈕的時候,設置當前頁面背景色為按鈕顏色,并發送通知,將前面兩個界面背景色也設置為選擇的顏色,程序框架和界面如圖所示
(1)注冊通知,在界面三的viewDidLoad方法中,為界面一和界面二注冊通知,當發送通知的時候,會去界面一和界面二中調用對應的方法
界面三中代碼:
- (void)viewDidLoad { [super viewDidLoad]; SecondViewController *secondVC = [self.navigationController.viewControllers objectAtIndex:1]; ViewController *firstVC = [self.navigationController.viewControllers firstObject]; //注冊通知 [[NSNotificationCenter defaultCenter] addObserver:secondVC selector:@selector(changeBgColor:) name:kNotificationName object:nil]; [[NSNotificationCenter defaultCenter] addObserver:firstVC selector:@selector(changeBgColor:) name:kNotificationName object:nil];}
ps:kNotificationName 是通過宏定義定義的字符串
(2) 在界面三點擊顏色按鈕時,換背景色,并且給界面一和界面二發送通知
界面三中代碼:
- (IBAction)chooseBgColor:(UIButton *)sender { NSArray *colorArray = @[[UIColor redColor],[UIColor blueColor],[UIColor greenColor],[UIColor purpleColor],[UIColor whiteColor],[UIColor blackColor],[UIColor orangeColor],[UIColor yellowColor],[UIColor brownColor]]; self.view.backgroundColor = [colorArray objectAtIndex:sender.tag-1]; //引發通知 [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:[colorArray objectAtIndex:sender.tag-1]]; }
(3)在界面一和界面二中處理通知,更改界面背景色
界面一和界面二中代碼:
-(void)changeBgColor:(NSNotification *)notification{ [self.view setBackgroundColor:notification.object];}
?。?)在界面三移除通知,移除通知一般在重寫父類的dealloc方法,但是arc方式下,在dealloc方法中不能調用父類的dealloc方法
界面三中代碼:
-(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:kNotificationName];}
疑問咨詢或技術交流,請加入官方QQ群: (452379712)
新聞熱點
疑難解答