1. 程式人生 > >消息通知機制(NSNotification和NSNotificationCenter)

消息通知機制(NSNotification和NSNotificationCenter)

idl 方法 lec lte nav mailto rst alter 5-0

作者:FlyElephant
出處:http://www.cnblogs.com/xiaofeixiang

iOS中委托模式和消息機制基本上開發中用到的比較多,一般最開始頁面傳值通過委托實現的比較多,類之間的傳值用到的比較多,不過委托相對來說只能是一對一,比如說頁面A跳轉到頁面B,頁面的B的值改變要映射到頁面A,頁面C的值改變也需要映射到頁面A,那麽就需要需要兩個委托解決問題。NSNotificaiton則是一對多註冊一個通知,之後回調很容易解決以上的問題。

基礎概念
iOS消息通知機制算是同步的,觀察者只要向消息中心註冊, 即可接受其他對象發送來的消息,消息發送者和消息接受者兩者可以互相一無所知,完全解耦。這種消息通知機制可以應用於任意時間和任何對象,觀察者可以有多個,所以消息具有廣播的性質,只是需要註意的是,觀察者向消息中心註冊以後,在不需要接受消息時需要向消息中心註銷,屬於典型的觀察者模式。
消息通知中重要的兩個類:

(1)NSNotificationCenter: 實現NSNotificationCenter的原理是一個觀察者模式,獲得NSNotificationCenter的方法只有一種,那就是[NSNotificationCenter defaultCenter] ,通過調用靜態方法defaultCenter就可以獲取這個通知中心的對象了。NSNotificationCenter是一個單例模式,而這個通知中心的對象會一直存在於一個應用的生命周期。

(2) NSNotification: 這是消息攜帶的載體,通過它,可以把消息內容傳遞給觀察者。

實戰演練
1.通過NSNotificationCenter註冊通知NSNotification,viewDidLoad中代碼如下:

1
2
3
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationFirst:) name:@"First" object:nil];

[[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);
}

-(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

消息通知機制(NSNotification和NSNotificationCenter)