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

个人对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);

}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值