NSNotificationCenter模式
来源:互联网 发布:betterment mac 编辑:程序博客网 时间:2024/05/18 01:27
通知 是在跳转控制器之间常用的传值代理方式,除了代理模式,通知更方便、便捷,一个简单的Demo实现通知的跳转传值.
在发送通知后,在所要接收的控制器中注册通知监听者,将通知发送的信息接收
输入所要发送的信息 ,同时将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];
注意
1、参数notificationObserver为要删除的观察者,一定不能置为nil。
2、如果发送的通知指定了object对象,那么观察者接收的通知设置的object对象与其一样,才会接收到通知,但是接收通知如果将这个参数设置为了nil,则会接收一切通知。object表示相应的对象。
3、观察者的SEL函数指针可以有一个参数,参数就是发送的死奥西对象本身,可以通过这个参数取到消息对象的userInfo,实现传值。
4、通知的发送若是在子线程,那么接收通知后的方法调用就是在子线程。
5、最后必须移除观察者。
6、通知在发出前一定要先有接收者。(待验证)
0 0
- NSNotificationCenter模式
- NSNotificationCenter的设计模式
- 设计模式 观察者 NSNotificationCenter
- NSNotificationCenter观察者模式
- NSNotificationCenter 与设计模式 (Observer)
- NSNotificationCenter 与设计模式 (Observer)
- NSNotificationCenter(观察者模式) 的使用
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSnotificationcenter
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- Android 的String资源格式化方法
- java学习总结(16.06.10~16.06.17)面向对象的三大特征——封装、继承、多态
- uva 10305(用DFS实现拓扑排序)
- 一次就好
- java 图形用户界面
- NSNotificationCenter模式
- 【Java学习-J.160601.0.20】Servlet生命周期
- Android进程分类与管理
- 二分查找,你真的掌握了吗?
- Java实现MD5消息摘要算法
- 数据结构_P14
- Android不依赖Activity的全局悬浮窗实现
- CodeForces 101D Castle(树形dp)
- java 计算器小程序