OC底层探索(十六) KVO底层原理

OC底层文章汇总

KVO全称KeyValueObserving,是苹果提供的一套事件通知机制。允许对象监听另一个对象特定属性的改变,并在改变时接收到事件。由于KVO的实现机制,所以对属性才会发生作用,一般继承自NSObject的对象都默认支持KVO

KVONSNotificationCenter都是iOS中观察者模式的一种实现。区别在于,相对于被观察者观察者之间的关系,KVO一对一的,而不一对多的。KVO对被监听对象无侵入性,不需要修改其内部代码即可实现监听。

KVO可以监听个属性的变化,也可以监听集合对象的变化。通过KVCmutableArrayValueForKey:等方法获得代理对象,当代理对象的内部对象发生改变时,会回调KVO监听的方法。集合对象包含NSArrayNSSet

KVO的使用

1、基本使用

@interface LGPerson : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *nick;
@property (nonatomic, copy) NSString *downloadProgress;
@property (nonatomic, assign) double writtenData;
@property (nonatomic, assign) double totalData;
@property (nonatomic, strong) NSMutableArray *dateArray;
@property (nonatomic, strong) LGStudent *st;
@end

static void *PersonNickContext = &PersonNickContext;

@interface LGViewController ()
@property (nonatomic, strong) LGPerson  *person;
@property (nonatomic, strong) LGStudent *student;
@end

@interface LGViewController ()
@property (nonatomic, strong) LGPerson  *person;
@property (nonatomic, strong) LGStudent *student;
@end

@implementation LGViewController

- (void)viewDidLoad {
   
    [super viewDidLoad];

    self.person  = [LGPerson new];

    // 1: context : 上下文
  
    [self.person addObserver:self forKeyPath:@"nick" options:NSKeyValueObservingOptionNew context:NULL];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
   
    self.person.nick = [NSString stringWithFormat:@"%@+",self.person.nick];
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
   
    // 性能 + 代码可读性
    NSLog(@"%@",change);
}


- (void)dealloc{
   
    [self.person removeObserver:
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值