iOS底层探索 之 KVC分析

246 阅读3分钟
KVC初探

根据官方文档我们来验证一下

set方法原文

image.png

HLPerson *person = [[HLPerson alloc] init];
[person setValue:@"Hardy" forKey:@"name"];

- (void)setName:(NSString *)name{
    NSLog(@"%s - %@",__func__,name);
}

- (void)_setName:(NSString *)name{
    NSLog(@"%s - %@",__func__,name);
}
//打印
-[HLPerson setName:] - Hardy
-[HLPerson _setName:] - Hardy

1、两个方法要是同时存在会先找找setName方法,要是没有setName才会执行_setName方法

+ (BOOL)accessInstanceVariablesDirectly{
    return YES;
}

2、accessInstanceVariablesDirectly 关闭或开启实例变量赋值
+ (BOOL)accessInstanceVariablesDirectly{
    return YES;//默认实现为YES
}

image.png

打印看下

 HLPerson *person = [[HLPerson alloc] init];
 [person setValue:@"Hardy" forKey:@"name"];
 NSLog(@"%@-%@-%@-%@",person->_name,person->_isName,person->name,person->isName);
输出:Hardy-(null)-(null)-(null)
注释掉  NSString *_name; 
打印NSLog(@"%@-%@-%@",person->_isName,person->name,person->isName);
输出:Hardy-(null)-(null)
get方法原文

image.png


    [self.person addObserver:self forKeyPath:@"nick" options:NSKeyValueObservingOptionNew context:NULL];

NULL 是C++的写法 void *类型穿NULL,要是id类型就传nil

- (**void**)observeValueForKeyPath:(**nullable** NSString *)keyPath 
ofObject:(**nullable** **id**)object change:(**nullable** NSDictionary<NSKeyValueChangeKey, **id**> *)change 
context:(**nullable** **void** *)context;

iOS 9 之后就不需要手动移除观察者了


应用案例
1、对可变数组的观察
    //先观察 再改变值
    [self.person addObserver:self forKeyPath:@"dateArray" options:(NSKeyValueObservingOptionNew) context:NULL];
    self.person.dateArray = [NSMutableArray array];
    [[self.person mutableArrayValueForKey:@"dateArray"] addObject:@"hardy"];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    NSLog(@"change--%@",change);
}

//打印
change--{
    kind = 1;
    new =     (
    );
}

change--{
    indexes = "<_NSCachedIndexSet: 0x6000010f0e40>[number of indexes: 1 (in 1 ranges), indexes: (0)]";
    kind = 2;
    new =     (
        hardy
    );
}

kind的值为什么是2?

NSKeyValueChangeKey jump

image.png

KVC 的底层原理

1、isa ->HLPerson->xxx类 ->中间产物是否销毁? 2、观察set方法 3、表面是对HLPerson赋值,那set方法是谁的? 4、HLPerson与xxx类 有什么关系? 5、监听接收到消息的时候 开始回调通知

是否有动态类处理?是否有生成set方法?

object_getClassName
    self.person = [[HLPerson alloc] init];
    [self.person addObserver:self forKeyPath:@"nickName" options:(NSKeyValueObservingOptionNew) context:NULL];

(lldb) p object_getClassName(self.person)
(const char * _Nonnull) $0 = 0x000000010d9144a2 "HLPerson"

//断点往下
(lldb) p object_getClassName(self.person)
(const char * _Nonnull) $1 = 0x0000600001e91a20 "NSKVONotifying_HLPerson"
NSKVONotifying
(lldb) p objc_getClass("NSKVONotifying_HLPerson")
(Class _Nullable) $1 = nil

意味在底层动态生成子类NSKVONotifying_HLPerson,父类为HLPerson

    self.person = [[HLPerson alloc] init];
    [self printClasses:[HLPerson class]];
    [self.person addObserver:self forKeyPath:@"nickName" options:(NSKeyValueObservingOptionNew) context:NULL];
    [self printClasses:[HLPerson class]];
    [self printClasses:objc_getClass("NSKVONotifying_HLPerson")];

//打印
classes -- (
    HLPerson,
    HLStudent
)
classes -- (
    HLPerson,
    "NSKVONotifying_HLPerson",
    HLStudent
)
classes -- (
    "NSKVONotifying_HLPerson"
)

pragma mark - 遍历类以及子类如下

- (void)printClasses:(Class)cls{
    // 注册类的总数
    int count = objc_getClassList(NULL, 0);
    // 创建一个数组, 其中包含给定对象
    NSMutableArray *mArray = [NSMutableArray arrayWithObject:cls];
    // 获取所有已注册的类
    Class* classes = (Class*)malloc(sizeof(Class)*count);
    objc_getClassList(classes, count);
    for (int i = 0; i<count; i++) {
        if (cls == class_getSuperclass(classes[i])) {
            [mArray addObject:classes[i]];
        }
    }
    free(classes);
    NSLog(@"classes -- %@", mArray);
}
NSKVONotifying_HLPerson 里面有什么呢?方法?
self.person = [[HLPerson alloc] init];  
 [self.person addObserver:self forKeyPath:@"name" options:(NSKeyValueObservingOptionNew) context:NULL];   
[self printClasses:[HLPerson class]];  
[self printClassAllMethod:objc_getClass("NSKVONotifying_HLPerson")]; 
[self printClassAllMethod:[HLStudent class]];

//打印
Method--class-0x7fff207bdb49
Method--dealloc-0x7fff207bd8f7
Method--_isKVOA-0x7fff207bd8ef
Method--setNickName:-0x1050444c0

pragma mark - 遍历方法-ivar-property如下

- (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(@"Method--%@-%p",NSStringFromSelector(sel),imp);
    }
    free(methodList);
}

image.png

//打印
{
    kind = 1;
    new = HL;
}
(lldb) p object_getClassName(self.person)
(const char * _Nonnull) $0 = 0x00006000020c2fc0 "NSKVONotifying_HLPerson"
(lldb) p object_getClassName(self.person)
(const char * _Nonnull) $1 = 0x00000001048e849b "HLPerson"  //isa指回来
NSKVONotifying_HLPerso 是否需要销毁呢?

销毁的时候把isa指回去 deallow是对象(NSKVONotifying_HLPerso的实例对象)的释放,而不是HLPerson

    self.person = [[HLPerson alloc] init];
    [self.person addObserver:self forKeyPath:@"nickName" options:(NSKeyValueObservingOptionNew) context:NULL];

//打印
HLViewController:classes = (
    HLPerson,
    HLStudent
)
(lldb) p self.person.class
(Class) $0 = HLPerson

打印的是HLPerson并不是NSKVONotifying_HLPerson,但底层实现真的是这样吗?

接着探索setter方法 我们先监听set方法 watchpoint 的使用


自定义KVC

我们来试着自定义一个KVC

**@interface** NSObject (HLKVC)

- (**void**)hl_setValue:(**nullable** **id**)value forKey:(NSString *)key{

    // 1: 非空判断
    **if** (key == **nil** || key.length == 0) {
        **return**;

    }

    // 2: setter set<Key>: or _set<Key>,

    // key 要大写

    NSString *Key = key.capitalizedString;

    // 拼接方法

    NSString *setKey = [NSString stringWithFormat:@"set%@:",Key];

    NSString *_setKey = [NSString stringWithFormat:@"_set%@:",Key];

    NSString *setIsKey = [NSString stringWithFormat:@"setIs%@:",Key];
    

    **if** ([**self** hl_performSelectorWithMethodName:setKey value:value]) {

        NSLog(@"*********%@**********",setKey);

        **return**;

    }**else** **if** ([**self** hl_performSelectorWithMethodName:_setKey value:value]) {

        NSLog(@"*********%@**********",_setKey);

        **return**;

    }**else** **if** ([**self** hl_performSelectorWithMethodName:setIsKey value:value]) {

        NSLog(@"*********%@**********",setIsKey);

        **return**;

    }

    

    // 3: 判断是否响应 accessInstanceVariablesDirectly 返回YES NO 奔溃

    // 判断是否能够直接赋值实例变量

    **if** (![**self**.class accessInstanceVariablesDirectly] ) {

        **@throw** [NSException exceptionWithName:@"HLUnknownKeyException" reason:[NSString stringWithFormat:@"****[%@ valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.****",**self**] userInfo:**nil**];

    }

    

    // 4: 间接变量

    // 获取 ivar -> 遍历 containsObjct -

    // 4.1 定义一个收集实例变量的可变数组

    NSMutableArray *mArray = [**self** getIvarListName];

    // _<key> _is<Key> <key> is<Key>

    NSString *_key = [NSString stringWithFormat:@"_%@",key];

    NSString *_isKey = [NSString stringWithFormat:@"_is%@",Key];

    NSString *isKey = [NSString stringWithFormat:@"is%@",Key];

    **if** ([mArray containsObject:_key]) {

        // 4.2 获取相应的 ivar

       Ivar ivar = class_getInstanceVariable([**self** class], _key.UTF8String);

        // 4.3 对相应的 ivar 设置值

       object_setIvar(**self** , ivar, value);

       **return**;

    }**else** **if** ([mArray containsObject:_isKey]) {

       Ivar ivar = class_getInstanceVariable([**self** class], _isKey.UTF8String);

       object_setIvar(**self** , ivar, value);

       **return**;

    }**else** **if** ([mArray containsObject:key]) {

       Ivar ivar = class_getInstanceVariable([**self** class], key.UTF8String);

       object_setIvar(**self** , ivar, value);

       **return**;

    }**else** **if** ([mArray containsObject:isKey]) {

       Ivar ivar = class_getInstanceVariable([**self** class], isKey.UTF8String);

       object_setIvar(**self** , ivar, value);

       **return**;

    }

    

    // 5:如果找不到相关实例

    **@throw** [NSException exceptionWithName:@"LGUnknownKeyException" reason:[NSString stringWithFormat:@"****[%@ %@]: this class is not key value coding-compliant for the key name.****",**self**,NSStringFromSelector( **_cmd**)] userInfo:**nil**];
}

未完待续........