通知 是在跳轉(zhuǎn)控制器之間常用的傳值代理方式什乙,除了代理模式,通知更方便已球、便捷臣镣,一個(gè)簡(jiǎn)單的Demo實(shí)現(xiàn)通知的跳轉(zhuǎn)傳值.
iOS通知傳值的使用
輸入所要發(fā)送的信息 辅愿,同時(shí)將label的值通過(guò)button方法調(diào)用傳遞,
- (IBAction)buttonClick:(id)sender {
//添加 字典忆某,將label的值通過(guò)key值設(shè)置傳遞
NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:self.textFieldOne.text,@"textOne",self.textFieldTwo.text,@"textTwo", nil];
//創(chuàng)建通知
NSNotification *notification =[NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dict];
//通過(guò)通知中心發(fā)送通知
[[NSNotificationCenter defaultCenter] postNotification:notification];
[self.navigationController popViewControllerAnimated:YES];
}
在發(fā)送通知后点待,在所要接收的控制器中注冊(cè)通知監(jiān)聽(tīng)者,將通知發(fā)送的信息接收
- (void)viewDidLoad {
[super viewDidLoad];
//注冊(cè)通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@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è)比較簡(jiǎn)單棒坏,直接調(diào)用該方法就行燕差。例如:
[[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];
注意參數(shù)notificationObserver為要?jiǎng)h除的觀察者,一定不能置為nil坝冕。