通知傳值我剛開始學(xué)的時(shí)候是看新浪博客的牛凱旋的舞虱,下面是根據(jù)那篇文章改編的
通知 是在跳轉(zhuǎn)控制器之間常用的傳值代理方式欢际,除了代理模式,通知更方便矾兜、便捷损趋,傳值的方式較于代理的一對一而言,它的傳值是一對多的椅寺。一個(gè)通知可以多個(gè)使用浑槽。但是相對于代理而言,通知傳值的速率較慢返帕。
下面是一個(gè)簡單的Demo實(shí)現(xiàn)通知的跳轉(zhuǎn)傳值.
輸入所要發(fā)送的信息 桐玻,同時(shí)將label的值通過button方法調(diào)用傳遞,
- (IBAction)buttonClick:(id)sender {
//添加字典荆萤,將label的值通過key值設(shè)置傳遞
NSDictionary*dict =[[NSDictionaryalloc]initWithObjectsAndKeys:self.textFieldOne.text,@"textOne",self.textFieldTwo.text,@"textTwo",nil];
//創(chuàng)建通知
NSNotification*notification =[NSNotificationnotificationWithName:@"tongzhi"object:niluserInfo:dict];
//通過通知中心發(fā)送通知
[[NSNotificationCenterdefaultCenter]postNotification:notification];
[self.navigationControllerpopViewControllerAnimated:YES];
}
在發(fā)送通知后搜立,在所要接收的控制器中注冊通知監(jiān)聽者糠悼,將通知發(fā)送的信息接收
- (void)viewDidLoad {
[superviewDidLoad];
//注冊通知
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(tongzhi:)name:@"tongzhi"object:nil];
}
- (void)tongzhi:(NSNotification*)text{
NSLog(@"%@",text.userInfo[@"textOne"]);
NSLog(@"-----接收到通知------");
}
移除通知:removeObserver:和removeObserver:name:object:
其中,removeObserver:是刪除通知中心保存的調(diào)度表一個(gè)觀察者的所有入口诚亚,而removeObserver:name:object:是刪除匹配了通知中心保存的調(diào)度表中觀察者的一個(gè)入口谨垃。
這個(gè)比較簡單罩驻,直接調(diào)用該方法就行咱士。例如:
[[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];
注意參數(shù)notificationObserver為要刪除的觀察者球订,一定不能置為nil。