IOS NSNotification Center 通知中樞的使用,iosnsnotification
通知中樞,它是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];}
(4)在介面三移除通知,移除通知一般在重寫父類的dealloc方法,但是arc方式下,在dealloc方法中不能調用父類的dealloc方法
介面三中代碼:
-(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:kNotificationName];}
想要瞭解更多內容的小夥伴,可以點擊查看源碼,親自運行測試。
疑問諮詢或技術交流,請加入官方QQ群: (452379712)
作者:傑瑞教育
出處:http://www.cnblogs.com/jerehedu/
本文著作權歸煙台傑瑞教育科技有限公司和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文串連,否則保留追究法律責任的權利。