做者:FlyElephant
出處:http://www.cnblogs.com/xiaofeixiangpost
iOS中委託模式和消息機制基本上開發中用到的比較多,通常最開始頁面傳值經過委託實現的比較多,類之間的傳值用到的比較多,不過委託相對來講只能是一對一,好比說頁面A跳轉到頁面B,頁面的B的值改變要映射到頁面A,頁面C的值改變也須要映射到頁面A,那麼就須要須要兩個委託解決問題。NSNotificaiton則是一對多註冊一個通知,以後回調很容易解決以上的問題。server
基礎概念
iOS消息通知機制算是同步的,觀察者只要向消息中心註冊, 便可接受其餘對象發送來的消息,消息發送者和消息接受者二者能夠互相一無所知,徹底解耦。這種消息通知機制能夠應用於任意時間和任何對象,觀察者能夠有多個,因此消息具備廣播的性質,只是須要注意的是,觀察者向消息中心註冊之後,在不須要接受消息時須要向消息中心註銷,屬於典型的觀察者模式。
消息通知中重要的兩個類:對象
(1)NSNotificationCenter: 實現NSNotificationCenter的原理是一個觀察者模式,得到NSNotificationCenter的方法只有一種,那就是[NSNotificationCenter defaultCenter] ,經過調用靜態方法defaultCenter就能夠獲取這個通知中心的對象了。NSNotificationCenter是一個單例模式,而這個通知中心的對象會一直存在於一個應用的生命週期。blog
(2) NSNotification: 這是消息攜帶的載體,經過它,能夠把消息內容傳遞給觀察者。生命週期
實戰演練
1.經過NSNotificationCenter註冊通知NSNotification,viewDidLoad中代碼以下:開發
1
2
3
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationFirst:) name:@"First" object:nil];rem
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSecond:) name:@"Second" object:nil];
第一個參數是觀察者爲自己,第二個參數表示消息回調的方法,第三個消息通知的名字,第四個爲nil表示表示接受全部發送者的消息~同步
回調方法:博客
1
2
3
4
5
6
7
8
9
10
11
12
13
-(void)notificationFirst:(NSNotification )notification{
NSString name=[notification name];
NSString *object=[notification object];
NSLog(@"名稱:%@----對象:%@",name,object);
}it
-(void)notificationSecond:(NSNotification )notification{
NSString name=[notification name];
NSString object=[notification object];
NSDictionary dict=[notification userInfo];
NSLog(@"名稱:%@----對象:%@",name,object);
NSLog(@"獲取的值:%@",[dict objectForKey:@"key"]);
}
2.消息傳遞給觀察者:
1
2
3
4
5
[[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.頁面跳轉:
1
2
3
4
-(void)pushController:(UIButton )sender{
ViewController customController=[[ViewController alloc]init];
[self.navigationController pushViewController:customController animated:YES];
}
4.銷燬觀察者
1
2
3
4
-(void)dealloc{
NSLog(@"觀察者銷燬了");
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
也能夠經過name單個刪除:
1
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"First" object:nil];
5.運行結果
1 2 3 4 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