NSNotificationCenter 通知中心
来源:互联网 发布:北京java周末班 编辑:程序博客网 时间:2024/06/05 02:13
通常我们在iOS中发生什么事件时该做什么是由Delegate实现的,例如View加载完后会触发ViewDidload.苹果还为我们提供了另一种通知响应方式 那就是NSNotificationCenter
与Delegate比较 NSNotificationCenter可以实现更大跨度的通信机制 可以为两个无引用关系的两个对象进行通信。
NSNotitficationCenter的通信原理使用了观察者模式:
注册观察者:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(execute:) name:@\"NOTIFICATION_NAME\" object:nil];
上面代码的意义为:观察者self 在收到名为@”NOTIFICATION_nNAME”的事件 时执行方法 @selector(execute:) 最后一个参数是表示会对那个发送者对象发出的事件作出响应,nil时表示接受所有发送者的事件 一般都为nil。
激发事件,即通知相应的观察者
[[NSNotificationCenter defaultCenter] postNotificationName:@\"NOTIFICATION_NAME\" object:nil];
这里的 object 参数对应到方法 - (void)execute:(NSNotification *)notification 里的 notification.object, name 就是 notification.name。
代码到这里,方法 - (void)execute:(NSNotification *)notification 就会得到执行了。
最后,你的观察者如果对一些事件没兴趣了,应该从 NotificationCenter 中移除掉
[[NSNotificationCenter defaultCenter] removeObserver:self name:@\"NOTIFICATION_NAME\" object:test];//object 与注册时相同
0 0
- 通知中心NSNotificationCenter
- 通知中心 NSNotificationCenter
- IOS NSNotificationCenter 通知中心
- 通知中心(NSNotificationCenter)
- NSNotificationCenter 通知中心
- 通知中心NSNotificationCenter
- NSNotificationCenter通知中心
- IOS NSNotificationCenter 通知中心
- NSNotificationCenter通知中心
- iOS通知中心(NSNotificationCenter)
- NSNotificationCenter(通知中心)
- 通知中心NSnotificationCenter
- iOS通知中心NSNotificationCenter
- 通知中心(NSNotificationCenter)
- 通知中心(NSNotificationCenter)
- NSNotificationCenter通知中心
- NSNotificationCenter通知中心
- 通知中心(NSNotificationCenter)
- springmvc+mybatis+maven+junit实现网页的增删查改
- spark(RDD之间的基本转换)
- 深入浅出UML类图
- php的tingkphp框架下的前后交互过程
- LeNet、AlexNet、VGG、ZF
- NSNotificationCenter 通知中心
- 动态获取程序的版本名称的方法以及dialog的简单用法以及两种上下文的区别
- 机器学习深度学习开源框架
- C++作业7
- hadoop namenode -format之后datanode无法启动问题
- 深入理解Linux内核 chap 3 进程
- 遗传算法入门到掌握(二)
- 一致性 hash 算法( consistent hashing )
- iOS方法:boundingRectWithSize:options:attributes:context:(计算文本尺寸)