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

IOS观察者模式_NSNotification,KVO,Delegate的使用理解

2014-08-15 18:09 302 查看
个人对IOS观察者模式的理解,就是一个被观察的对象和一个观察对象,其实总觉得观察这个词不是很准确,通知这个词更为准确,三种方法中,除了NSNotification是广播似的传播消息外,KVO和Delegate都是一对一的传播,Delegate大家已经用得很熟了,我只说说NSNotification和Delegate,其实是Delegate用得熟悉,但是说着就很绕了,而且还不一定说得清楚。

NSNotifiction

该方式是相对简单地,不用对象之间的相互引用,只有在同一个应用程序内,都能够通知得到,只要notifictionWithName相同,所有观察着都能被通知到

注册一个被监听对象,newNotification是被监听对象识别的标识,object是传出的参数

[[NSNotificationCenter defaultCenter] postNotificationName:@"newNotification" object:@"change"];

或者

NSNotification *notification=[NSNotificationnotificationWithName:@"newNotification"object:@"change"];

[[NSNotificationCenter defaultCenter] postNotification:notification];
注册一个监听者

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationCenter:) name:@"newNotification" object:nil];

//接到通知后调用的方法
- (void)notificationCenter:(NSNotification *)notification
{

NSString *string=(NSString *)notification;

NSLog(@"%@",string);
}

//下面是输出内容
{name = newNotification; object = change}

KVO --Key-Value Observing Programming Guide

通过KVO,某个对象中的特定属性发生了改变,别的对象可以获得通知,几乎在OC里面每一个类都存在这两个方法
- (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;

//给对象添加一个监视器,在keyPath属性做出相应地options动作后就会调用observer类的方法observeValueForKeyPath:
ofObject: change:e context:

//声明一个内 存在changeable属性

@interface KVOSubject : NSObject
@property (nonatomic,strong) NSString *changeable;
@end

@implementation KVOSubject
@end

在当前当前对象触发方法内实例KVOSubject

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

KVOSubject *kvoSubj = [[KVOSubject alloc] init];
[kvoSubj addObserver:self forKeyPath:@"changeable" options:NSKeyValueObservingOptionNew context:nil];
kvoSubj.changeable = @"新的一个值";
[kvoSubj setValue:@"新的一个值" forKey:@"changeable"];
[kvoSubj removeObserver:self forKeyPath:@"changeable"];
}
//当触发屏幕后该类就会被调用

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"%@",keyPath);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: