iOS开发总结(A0)- NSNotification , KVO, 及 Delegate

NSNotification, KVO(key value observing ) 和 Delegate 都可以用来对象之间的通信。

一、概念

NSNotification :

NSNotification 类似收听电台,电台发送通知,用户收听

每个Notification有一个名称,若某个对象为该Notification的观察者(即一直监听该notificaiton是否发送),当Notification 发送后,该对象会收到(同时所有该Notification的观察者都会收到)。

 

KVO:键-值观察

如果对象a对对象b某个property很感兴趣,需要根据property的变化做一些事情,那么键值观察比较适合。

对象a 成为对象b的某个property观察者后,每当b的这个property变化,a就会知道,然后a可以做相应的处理。

比如对象b代表了一个人的所有信息,如年龄,身高,头像等,对象a 是展示对象b头像的view,

对象a需要根据b头像的变化更新展示新头像。那么对象a可以称为对象b头像property 的观察者,一旦头像数据变化,对象a将会得知,然后可以更新头像。

(NSUserDefault 的key也可用于键值观察,具体见官方文档) 

delegate 

形象的说,a需要处理一件事件,但不知怎么处理,就把事件(什么事情及必要参数)扔给他的delegate 处理。

二者是一对一的关系, cocoa 中有大量的应用,大多结合protocol使用

(应用中大多是一对一的使用。必要的时候,也可以维护一个 delegate 数组(可称作observers),有时很方便)

 

二、用法

如何使用Notification?

解决两个问题就可以了:1)如何送Notification  2)如何接受Notification

1)发送Notification

所有Notification由 NSNotificationCenter发送,

[[NSNotificationCenterdefaultCenter] postNotificationName:@"mynotificaiton"object:niluserInfo:nil];

(其他发送方法参考文档)

2) 如何接收Notification?

首先得称为Notification的收听者,通过以下方法收听:

[[NSNotificationCenterdefaultCenter]addObserver:self selector:@selector(handleNotification:) name:@"mynotificaiton"object:nil];
收到mynotificaiton后,自动执行handleNotification:方法
注意:
1)有addObserver...,就应该有removeObserve... 否则可能出现内存泄漏,我想是因为NSNotificationCenter 保持了 observer 的引用
所以在ViewController中,viewWillAppear 和 viewWillDisappear等配对的方法 是一个很好的 add 和remove observer 的地方
2)如果NSNotificationCenter 在发送mynotification 之后才添加了observe,那么该observer 是收不到添加之前的mynotificaiton的.
 
 
如何使用KVO ? 
假设对象a需要观察对象b的property photo.
1)添加对象a作为对象b property photo 的观察者

[objectb addObserver:objecta forKeyPath:@“photo" options: NSKeyValueObservingOptionNew context:nil];

(至少要在objecta dealloc之前要removeobserver,否则可能出现内存泄漏)

 

2)对象a要实现这个方法

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

当object 的keypath内容变化后,对象a 自动调用该方法.

但是如果对象b keypath的内容不是通过kvc的方式变化的,对象a是观察不到的

3) objective-c 是如何KVO机制的?

正在学习,

http://www.jianshu.com/p/37a92141077e

http://www.jianshu.com/p/829864680648

原文地址:https://www.cnblogs.com/beddup/p/4612150.html