美文网首页
iOS技术总结-KVC与KVO

iOS技术总结-KVC与KVO

作者: zhq1992 | 来源:发表于2021-09-12 12:48 被阅读0次

    一.KVO

    1. KVO的全称是Key-Value Observing,俗称“键值监听”,可以用于监听某个对象属性值的改变,不监听成员变量
    KVO的使用不再赘述,见如下代码

    #import "ViewController.h"
    
    @interface Person : NSObject
    {
        @public
        int age;
    }
    
    @property (nonatomic, copy) NSString *name;
    
    @end
    
    @implementation Person
    
    - (void)setName:(NSString *)name{
        _name = name;
    }
    
    @end
    
    
    @interface ViewController ()
    
    @property (nonatomic, strong) Person *person1;
    @property (nonatomic, strong) Person *person2;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        self.person1 = [[Person alloc] init];
        self.person2 = [[Person alloc] init];
        
        self.person1->age = 1;
        self.person1.name = @"person1";
        
        self.person2->age = 2;
        self.person2.name = @"person2";
        
        // 给person1对象添加KVO监听
        NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
        [self.person1 addObserver:self forKeyPath:@"name" options:options context:@"123"];
        [self.person1 addObserver:self forKeyPath:@"age" options:options context:NULL];
    }
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        // NSKVONotifying_Person是使用Runtime动态创建的一个类,是Person的子类
        
        // self.person1.isa == NSKVONotifying_Person
        self.person1->age = 3;
        self.person1.name = @"Jack";
    
        // self.person2.isa = MJPerson
        self.person2->age = 4;
        self.person2.name = @"Marry";
    }
    
    - (void)dealloc {
        [self.person1 removeObserver:self forKeyPath:@"age"];
        [self.person1 removeObserver:self forKeyPath:@"name"];
    
    }
    
    // 当监听对象的属性值发生改变时,就会调用
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
    {
        NSLog(@"监听到%@的%@属性值改变了 - %@ - %@", object, keyPath, change, context);
    }
    

    打印情况如下


    截屏2021-09-12 上午10.42.44.png

    可以看出只监听了属性name,没有监听成员变量age

    2.苹果官方文档可以看到KVO是使用isa-swizzling技术实现的,当观察者注册时,被观察者的isa指针被修改,指向一个中间类而不是真正的类。因此,isa指针指向的不一定是实例对象的真正类,您应该使用class方法来确定实例对象的类。

    截屏2021-09-12 上午11.23.11.png

    通过断点可以验证person1和person2的isa指向

    截屏2021-09-12 上午11.35.18.png

    3. 打印NSKVONotifying_Person的方法列表

     [self printClassAllMethod:objc_getClass("NSKVONotifying_Person")];
    
    - (void)printClassAllMethod:(Class)cls{
        unsigned int count = 0;
        Method *methodList = class_copyMethodList(cls, &count);
        for (int i = 0; i<count; i++) {
            Method method = methodList[i];
            SEL sel = method_getName(method);
            IMP imp = class_getMethodImplementation(cls, sel);
            NSLog(@"%@-%p",NSStringFromSelector(sel),imp);
        }
        free(methodList);
    }
    

    从结果可以看出NSKVONotifying_Person重写了setName方法

    截屏2021-09-12 下午12.25.42.png

    4.setName中打一个断点,可以看到_NSSetObjectValueAndNotify方法的调用,在setter方法前后,调用了NSKeyValueWillChangeNSKeyValueDidChangeBySetting

    WX20210912-123044.png WX20210912-122804.png

    实际上若被观察的类型是NSString,那么重写的方法的实现会指向_NSSetObjectValueAndNotify这个函数,若是Bool类型,那么重写的方法的实现会指向_NSSetBoolValueAndNotify这个函数,这个函数里会调用willChangeValueForKey:didChangeValueForKey:,并且会在这2个方法调用之间,调用父类set方法的实现,didChangeValueForKey:内部会调用observer的observeValueForKeyPath:ofObject:change:context:方法

    5.手动触发KVO
    KVO属性发生变化时,会自动调用willChangeValueForKey:didChangeValueForKey:,可以通过重写automaticallyNotifiesObserversForKey:返回NO关闭自动调用,并手动调用willChangeValueForKey:didChangeValueForKey:

    - (void)setName:(NSString *)name{
        [self willChangeValueForKey:@"name"];
        _name = name;
        [self didChangeValueForKey:@"name"];
    }
    
    + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key{
        return NO;
    }
    

    6.总结
    iOS用什么方式实现对一个对象的KVO?(KVO的本质是什么?)
    答:利用RuntimeAPI动态生成一个子类,并且让instance对象的isa指向这个全新的子类,当修改instance对象的属性时,会调用Foundation的_NSSetXXXValueAndNotify函数,这个函数里会按顺序调用willChangeValueForKey:父类原来的setterdidChangeValueForKey:didChangeValueForKey:内部会触发监听器(Oberser)的监听方法( observeValueForKeyPath:ofObject:change:context:)

    如何手动触发KVO?
    答:手动调用willChangeValueForKey:didChangeValueForKey:

    直接修改成员变量会触发KVO吗?
    答:不会触发KVO

    二、KVC

    KVC的全称是Key-Value Coding,俗称“键值编码”,可以通过一个key来访问某个属性,常见的API有

    - (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
    - (void)setValue:(id)value forKey:(NSString *)key;
    - (id)valueForKeyPath:(NSString *)keyPath;
    - (id)valueForKey:(NSString *)key; 
    
    

    KVC的取值和赋值原理可以参考苹果官方文档

    setter
    getter

    相关文章

      网友评论

          本文标题:iOS技术总结-KVC与KVO

          本文链接:https://www.haomeiwen.com/subject/impowltx.html