(转)NSNotification、delegate和KVO的区别
来源:互联网 发布:刘梦溪 知乎 编辑:程序博客网 时间:2024/06/05 04:02
1.效率肯定是delegate比nsnotification高。
2. delegate方法比notification更加直接,最典型的特征是,delegate方法往往需要关注返回值, 也就是delegate方法的结果。比如-windowShouldClose:,需要关心返回的是yes还是no。所以delegate方法往往包含 should这个很传神的词。也就是好比你做我的delegate,我会问你我想关闭窗口你愿意吗?你需要给我一个答案,我根据你的答案来决定如何做下一 步。相反的,notification最大的特色就是不关心接受者的态度, 我只管把通告放出来,你接受不接受就是你的事情,同时我也不关心结果。所以notification往往用did这个词汇,比如 NSWindowDidResizeNotific
简明概要的说明了KVO和NSNotification的区别:
和delegate一样,KVO和NSNotification的作用也是类与类之间的通信,与delegate不同的是1)这两个都是负责发出通知,剩下的事情就不管了,所以没有返回值;2)delegate只是一对一,而这两个可以一对多。这两者也有各自的特点。
1)KVO的使用:
被观察者发出
然后只要被观察者的keyPath值变化(注意:单纯改变其值不会调用此方法,只有通过getters和setters来改变值才会触发KVO),就会在观察者里调用方法observeValueForKeyPath:ofObject:change:context:
因此观察者需要实现方法
- 这 些代码都只需在观察者里进行实现,被观察者不用添加任何代码,所以谁要监听谁注册,然后对响应进行处理即可,使得观察者与被观察者完全解耦,运用很灵活很 简便;但是KVO只能检测类中的属性,并且属性名都是通过NSString来查找,编译器不会帮你检错和补全,纯手敲所以比较容易出错。
- 2)NSNotification的使用
- 这里的通知不是由被观察者发出,而是由NSNotificationCenter来统一发出,而不同通知通过唯一的通知标识名notificationName来区分,标识名由发送通知的类来起。
- 首先被观察者自己在必要的方法A里,通过方法postNotificationName:object:来发出通知notificationName这样发送通知者这边的工作就完成了,每次A被调用,就会发送一次通知notificationName。
- 然后谁要监听A的变化,就通过[NSNotificationCenter defaultCenter]的方法addObserver:selector:name:object:为观察者注册监听name为notificationName的通知然后每次发出name为notificationName的通知时,注册监听后的观察者就会调用其自己定义的方法notificationSelector来进行响应。
- NSNotification的特点呢,就是需要被观察者先主动发出通知,然后观察者注册监听后再来进行响应,比KVO多了发送通知的一步,但是其优点是监听不局限于属性的变化,还可以对多种多样的状态变化进行监听,监听范围广,使用也更灵活。
- (转)NSNotification、delegate和KVO的区别
- (转)NSNotification、delegate和KVO的区别
- 转)NSNotification、delegate和KVO的区别
- 笔记:NSNotification,delegate和KVO的区别(转)
- NSNotification、delegate和KVO的区别
- NSNotification、delegate和KVO的区别
- NSNotification、delegate和KVO的区别
- NSNotification、delegate和KVO的区别
- NSNotification、delegate和KVO的区别
- NSNotification、delegate和KVO的区别
- NSNotification、delegate和KVO的区别
- NSNotification、delegate和KVO的区别
- NSNotification、delegate和KVO的区别
- NSNotification、delegate和KVO的区别
- NSNotification、delegate和KVO的区别
- NSNotification、delegate和KVO的区别
- NSNotification、delegate和KVO的区别
- NSNotification、delegate和KVO的区别
- 2014_03_30工作日志:error C2146: syntax error : missing ';' before identifier 'LPTSTR'
- oracle数据库实例的理解
- 黑马程序员---Java高新技术学习笔记-1
- 父类引用指向子类对象
- 黑马程序员---Java高新技术学习笔记-2
- (转)NSNotification、delegate和KVO的区别
- scrollBar的使用及对话框的标准滚动的使用
- 线程、线程句柄、线程ID的关系
- 第五周(项目二)——分数类的雏形。
- eclipse-以指定颜色高亮显示选中关键字
- 黑马程序员---Java高新技术学习笔记-3
- 第三章 DispatcherServlet详解 ——跟开涛学SpringMVC
- OFBiz entity engine中的设计模式总结
- 链表:基本例程的实现