您的位置:首页 > 移动开发 > IOS开发

ios 观察者模式(Notification、KVO)

2015-02-26 00:00 267 查看
摘要: 什么是观察者模式?
我的理解是:1、不需要理解中间过程。2、有两个对象A,B ...这里的A...

1、Notification

首先:在B中注册:

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;

例如:

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name: kReachabilityChangedNotification
object: nil];

这里的观察对象是self本身,就是我说的b, 观察后响应的方法是

- (void)reachabilityChanged: (NSNotification*)note
{
[self updateInterfaceWithReachability];
}

里面的name是消息通知的标识(nsstring)的,用来识别是哪个发来的通知

object一般可以写nil,即发送消息的对象

其次:就是a发送消息

发送消息的发放主要有

- (void)postNotification:(NSNotification *)notification;
- (void)postNotificationName:(NSString *)aName object:(id)anObject;
- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;

比如,在苹果提供网络监测的Reachability中

[[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object: noteObject];

没当这个语句跑一次,就会通知消息给b,响应前面注册的aSelector方法

即实现了通知效果

最后就是移除这个观察者模式的方法

- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;


2、kvo

这里我说简单些

第一步当然也是注册,后面是响应调用的方法

- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;

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

跳到NSKeyValueObserving.h文件里面还有其他几种addObserver的方法,和删除观察者的方法,,

上一个列子

[a addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"改变");
}

上面的a其实是一个view。也是被观察者a,self是观察者b,@“frame”是a的一个属性,nskeyvalueobservingoptiongnew是改变后的frame新值,当a的frame改变后,就会触发

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

方法。方法里面的change携带frame改变信息

最后如果不要管着者了,,记得 remove掉,NSKeyValueObserving.h文件里面有相对用的remove方法,

如有转载,不用表明出处,谢谢!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息