KVO

2018-05-16  本文已影响0人  愤怒小鸟飞呀飞
KVO 概念

KVO即Key-Value-Observing,顾名思义用于键值观察

//通过此方法即可添加对象的观察者
- (void)addObserver:(NSObject *)observer
         forKeyPath:(NSString *)keyPath
            options:(NSKeyValueObservingOptions)options
            context:(void *)context;
使用场景

1、NSProgress监听进度变化
2、监听对象属性值的变化
eg.

@interface Person : NSObject{
    NSString *_name;
}
@property(nonatomic,copy)NSString *name;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    _person = [[Person alloc] init];
    _person.name = @"huahua";
    [_person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
      [_person setValue:@"newHuahua" forKey:@"name"];
}

//观察者需要实现的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"observer receive change infomation");
}
实现原理解析

原来,这个中间类继承自原本的那个类。不仅如此,apple还重写了 -class方法,企图欺骗我们这个类没有变,就是原本那个类。
eg.原类 Person,派生类NSKVONotifying_Person

参考链接:https://www.zybuluo.com/MicroCai/note/66738
https://www.jianshu.com/p/829864680648
http://tech.glowing.com/cn/implement-kvo/

上一篇 下一篇

猜你喜欢

热点阅读