iOS利用通知(NSNotification)进行传值
2015-08-25 14:55
417 查看
通知 是在跳转控制器之间常用的传值代理方式,除了代理模式,通知更方便、便捷,一个简单的Demo实现通知的跳转传值.
iOS通知传值的使用
输入所要发送的信息 ,同时将label的值通过button方法调用传递,
- (IBAction)buttonClick:(id)sender {
//添加 字典,将label的值通过key值设置传递
NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:self.textFieldOne.text,@"textOne",self.textFieldTwo.text,@"textTwo", nil];
//创建通知
NSNotification *notification =[NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dict];
//通过通知中心发送通知
[[NSNotificationCenter defaultCenter] postNotification:notification];
[self.navigationController popViewControllerAnimated:YES];
}
在发送通知后,在所要接收的控制器中注册通知监听者,将通知发送的信息接收
- (void)viewDidLoad {
[super viewDidLoad];
//注册通知
[[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:是删除通知中心保存的调度表一个观察者的所有入口,而removeObserver:name:object:是删除匹配了通知中心保存的调度表中观察者的一个入口。
这个比较简单,直接调用该方法就行。例如:
[[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];
注意参数notificationObserver为要删除的观察者,一定不能置为nil。
iOS通知传值的使用
输入所要发送的信息 ,同时将label的值通过button方法调用传递,
- (IBAction)buttonClick:(id)sender {
//添加 字典,将label的值通过key值设置传递
NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:self.textFieldOne.text,@"textOne",self.textFieldTwo.text,@"textTwo", nil];
//创建通知
NSNotification *notification =[NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dict];
//通过通知中心发送通知
[[NSNotificationCenter defaultCenter] postNotification:notification];
[self.navigationController popViewControllerAnimated:YES];
}
在发送通知后,在所要接收的控制器中注册通知监听者,将通知发送的信息接收
- (void)viewDidLoad {
[super viewDidLoad];
//注册通知
[[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:是删除通知中心保存的调度表一个观察者的所有入口,而removeObserver:name:object:是删除匹配了通知中心保存的调度表中观察者的一个入口。
这个比较简单,直接调用该方法就行。例如:
[[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];
注意参数notificationObserver为要删除的观察者,一定不能置为nil。
相关文章推荐
- IOS 学习 模型初始化的方法
- IOS 学习 执行动画
- iOS 7 viewcontroller新增属性automaticallyAdjustsScrollViewInsets
- [iOS] #运行时编程# Block植入
- iOS 常用的宏定义
- iOS第三方框架集合
- IOS 学习记录 表格单元格放入缓存池
- IOS 学习 字典转模型
- ios自定义构造方法
- iOS利用通知(NSNotification)进行传值
- iOS 辛格尔顿
- ios语法——委托和协议
- 条形码、二维码扫描
- ios日期格式转换
- iO7以上CIFilter生成二维码(备忘) 此博文包含图片 (2015-04-24 14:48:25)转载
- iOS多线程编程之Grand Central Dispatch(GCD)介绍和使用
- 使用Nagios搭建监控服务器
- iOS中Foundation的常见知识点
- IOS 多线程(4) --线程通讯
- iOS中属性与成员变量的区别