iOS中委托模式和消息機制基本上開發中用到的比較多,一般最開始頁面傳值通過委托實現的比較多,類之間的傳值用到的比較多,不過委托相對來說只能是一對一,比如說頁面A跳轉到頁面B,頁面的B的值改變要映射到頁面A,頁面C的值改變也需要映射到頁面A,那么就需要需要兩個委托解決問題。NSNotificaiton則是一對多注冊一個通知,之后回調很容易解決以上的問題。
基礎概念
iOS消息通知機制算是同步的,觀察者只要向消息中心注冊, 即可接受其他對象發送來的消息,消息發送者和消息接受者兩者可以互相一無所知,完全解耦。
這種消息通知機制可以應用於任意時間和任何對象,觀察者可以有多個,所以消息具有廣播的性質,只是需要注意的是,觀察者向消息中心注冊以后,在不需要接受消息時需要向消息中心注銷,屬於典型的觀察者模式。
消息通知中重要的兩個類:
(1)NSNotificationCenter: 實現NSNotificationCenter的原理是一個觀察者模式,獲得NSNotificationCenter的方法只有一種,那就是[NSNotificationCenter defaultCenter] ,通過調用靜態方法defaultCenter就可以獲取這個通知中心的對象了。NSNotificationCenter是一個單例模式,而這個通知中心的對象會一直存在於一個應用的生命周期。
(2) NSNotification: 這是消息攜帶的載體,通過它,可以把消息內容傳遞給觀察者。
實戰演練
1.通過NSNotificationCenter注冊通知NSNotification,viewDidLoad中代碼如下:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationFirst:) name:@"First" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSecond:) name:@"Second" object:nil];
第一個參數是觀察者為本身,第二個參數表示消息回調的方法,第三個消息通知的名字,第四個為nil表示表示接受所有發送者的消息~
回調方法:
-(void)notificationFirst:(NSNotification *)notification{ NSString *name=[notification name]; NSString *object=[notification object]; NSLog(@"名稱:%@----對象:%@",name,object); } -(void)notificationSecond:(NSNotification *)notification{ NSString *name=[notification name]; NSString *object=[notification object]; NSDictionary *dict=[notification userInfo]; NSLog(@"名稱:%@----對象:%@",name,object); NSLog(@"獲取的值:%@",[dict objectForKey:@"key"]); }
2.消息傳遞給觀察者:
[[NSNotificationCenter defaultCenter] postNotificationName:@"First" object:@"博客園-Fly_Elephant"]; NSDictionary *dict=[[NSDictionary alloc]initWithObjects:@[@"keso"] forKeys:@[@"key"]]; [[NSNotificationCenter defaultCenter] postNotificationName:@"Second" object:@"http://www.cnblogs.com/xiaofeixiang" userInfo:dict];
3.頁面跳轉:
-(void)pushController:(UIButton *)sender{ ViewController *customController=[[ViewController alloc]init]; [self.navigationController pushViewController:customController animated:YES]; }
4.銷毀觀察者
-(void)dealloc{ NSLog(@"觀察者銷毀了"); [[NSNotificationCenter defaultCenter] removeObserver:self]; }
也可以通過name單個刪除:
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"First" object:nil];
5.運行結果
2015-04-26 15:08:25.900 CustoAlterView[2169:148380] 觀察者銷毀了 2015-04-26 15:08:29.222 CustoAlterView[2169:148380] 名稱:First----對象:博客園-Fly_Elephant 2015-04-26 15:08:29.222 CustoAlterView[2169:148380] 名稱:Second----對象:http://www.cnblogs.com/xiaofeixiang 2015-04-26 15:08:29.223 CustoAlterView[2169:148380] 獲取的值:keso