iOS KVO深入浅出

2020-10-28  本文已影响0人  Johnny_Z

一 、KVO 是什么?


官方文档中的描述为

Key-value observing is a mechanism that allows objects to be notified of changes to specified properties of other objects.

KVO是一套通知机制,这套机制让一个对象可以收到一个通知,这个通知描述的是另一个对象它的属性发生的变化。(自己对照的英文理解可能会更好)

二、 怎么使用KVO


1. 举个🌰

我们拿官方例子来描述,Person对象监听Account对象

Art/kvo_objects_properties.png

2. context理解

官方文档描述中

The context pointer in the addObserver:forKeyPath:options:context: message contains arbitrary data that will be passed back to the observer in the corresponding change notifications. You may specify NULL and rely entirely on the key path string to determine the origin of a change notification, but this approach may cause problems for an object whose superclass is also observing the same key path for different reasons.
A safer and more extensible approach is to use the context to ensure notifications you receive are destined for your observer and not a superclass.

大意就是:你和你的父类可能同时监听了相同的key path;如果没有上下文context的支持无法做到区分。

//child继承于person
//context声明定义
static void *PersonContext = &PersonContext;
static void *ChildContext = &ChildContext;
...
//添加观察者
[account addObserver:person forKeyPath:@"balance" options:NSKeyValueObservingOptionNew context:PersonContext];
[account addObserver:child forKeyPath:@"balance" options:NSKeyValueObservingOptionNew context:ChildContext];
...
//实现通知回调
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if (context == PersonContext) {
        NSLog(@"%@", change);
    } else if (context == ChildContext) {
        NSLog(@"%@", change);
    }
}

通过context就能很方便地处理通知了

3. 善后处理-移除观察者的纯粹性和必要性

在移除observer的描述中有这么几段话

image.png

4. 手动触发KVO

1、首先通过automaticallyNotifiesObserversForKey类方法屏蔽某个属性的自动通知逻辑

+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
    if ([key isEqualToString:@"name"]) {
        return NO;
    }
    return [super automaticallyNotifiesObserversForKey:key];
}

2、修改该属性setter方法的实现,手动callwillChangeValueForKeydidChangeValueForKey两个方法

- (void)setName:(NSString *)name {
    [self willChangeValueForKey:@"name"];
    _name = name;
    [self didChangeValueForKey:@"name"];
}

三、KVO的底层原理 :中间派生类(isa-swizzling)


1. 回到了我们的官方文档

KVO 底层原理

文中的大意是

2.实操演示

大家可能还不是很好的理解上面这段话的第3点,不过幸好有我带领大家分析;经过我下面的演示可能你就会有一个深入的了解


运行结果

在运行过程中我们可以看到:

这中间person类的名字变化其实就是isa指针进行了isa-swizzling

3、深入中间派生类-NSKVONotifying_XXX

LGPerson.h定义

@interface LGPerson : NSObject{
    @public
    NSString *name;
}
@property (nonatomic, copy) NSString *nickName;

@end

这其中有一个成员变量name和一个属性nickName

runtime机制打印class中的方法

- (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);
}

添加namenickName的观察,打印原始类和中间派生类的方法

image.png

大家在图中可以清晰的看到

总结


1、理解KVO使用:注册,回调,移除。特别是注册和移除需小心使用
2、automaticallyNotifiesObserversForKey可以修改可接受观察的属性
3、NSKVONotifying_XXX派生类其实就重写或实现了setterclassdealloc_isKVOA,即KVO 应用了isa-swizzling的技术

上一篇 下一篇

猜你喜欢

热点阅读