KVC原理

一.KVC的setValue:forKey:底层执行

1.优先查找setter方法
先查找是否有setKey方法,如果没有,查找是否有_setKey方法,如果还没有找到,查找是否有setIsKey方法

2.setter方法没有查找到,会调用 + (BOOL)accessInstanceVariablesDirectly方法,默认返回YES,表示可以直接通过实例变量设置值。
如果返回YES,会查找实例变量,不过,它有查找优先级。先查找_key,没有找到,会查找_isKey,若没有找到,查找是否有key,如还没有找到,会查找isKey。找到实例变量,给这个实例变量设置值,若最后还没有找到,进入步骤3
如果返回NO,进入步骤3

3.以上都没有找到,执行 setValue:forUndefinedKey:方法
3.1 如果没有重写该方法,会调用系统的,并抛出异常
3.2 如果重写了,执行你重写的这个方法,将这种情况交由你来处理,不会抛出异常,中断程序。

KVC设值流程图
KVC of setValue.jpeg

二.KVC的valueForKey:底层执行

1.优先查找getter方法
先查找getKey,没有找到,查找key,如没有找到,继续查找isKey,以上还没有找到,会先查找_getKey,再查找_key。找到了执行该方法,并返回值。

2.查找响应集合NSArray所有方法的代理对象
先查找是否有countOfKey方法,若没有,直接进入步骤5。如果有countOfKey方法,继续查找是否有objectInKeyAtIndex:/ keyAtIndexes:方法,如果有,返回一个可以响应集合NSArray所有方法的代理对象(实际是一个NSKeyValueArray对象,它是NSArray的子类)。使用这个对象调用NSArray的所有方法,会转换为调用countOfKey方法、objectInKeyAtIndex:/ keyAtIndexes:方法组合的形式来创建键值编码对象。
注意:
1.如果objectInKeyAtIndex:、keyAtIndexes:方法都存在,调用objectAtIndex:方法,会触发objectInKeyAtIndex:方法,调用objectsAtIndexes:方法,会触发keyAtIndexes:方法。
2.如果只有objectInKeyAtIndex:方法,调用objectAtIndex:objectsAtIndexes:方法,都会触发objectInKeyAtIndex:方法,只不过,调用objectsAtIndexes:方法返回的结果是空数组
3.如果只有keyAtIndexes:方法,调用objectAtIndex:objectsAtIndexes:方法,都会触发keyAtIndexes:方法。

3.查找响应集合NSSet所有方法的代理对象
先查找是否有countOfKey方法,若没有,直接进入步骤5。如果有countOfKey方法,继续查找是否有enumeratorOfKey:/ memberOfKey:方法,如果有,返回一个可以响应集合NSSet所有方法的代理对象。使用这个对象调用NSSet的所有方法,会转换为调用countOfKey方法、enumeratorOfKey:/ memberOfKey:方法组合的形式来创建键值编码对象。

4.以上都没有找到,调用+ (BOOL)accessInstanceVariablesDirectly方法,默认返回 YES,表示可以直接通过实例变量设置值。
如果返回YES,会查找实例变量,不过,它有查找优先级。先查找_key,没有找到,会查找_isKey,若没有找到,查找是否有key,如还没有找到,会查找isKey。找到实例变量,返回获取到的值,若最后还没有找到,进入步骤5
如果返回NO,进入步骤5

5.以上都没有找到,执行valueForUndefinedKey:方法
5.1 如果没有重写该方法,会调用系统的,并抛出异常
5.2 如果重写了,执行你重写的这个方法,将这种情况交由你来处理,不会抛出异常,中断程序。

KVC取值流程图
KVC of valueForKey.jpeg

三、根据原理,自己实现KVC

模拟KVC设置值

- (void)setCWValue:(id)value forKey:(NSString *)key
{
    if (!value || !key) {
        return;
    }
    
    //查找setter方法:setKey、_setKey、setIskey
    NSString *capitalizedString = key.capitalizedString;
    NSString *setKey = [NSString stringWithFormat:@"set%@:",capitalizedString];
    NSString *_setKey = [NSString stringWithFormat:@"_set%@:",capitalizedString];
    NSString *setIsKey = [NSString stringWithFormat:@"setIs%@:",capitalizedString];
    
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    if ([self respondsToSelector:NSSelectorFromString(setKey)]) {
        [self performSelector:NSSelectorFromString(setKey) withObject:value];
        return;
    } else if ([self respondsToSelector:NSSelectorFromString(_setKey)]) {
        [self performSelector:NSSelectorFromString(_setKey) withObject:value];
        return;
    }else if ([self respondsToSelector:NSSelectorFromString(setIsKey)]) {
        [self performSelector:NSSelectorFromString(setIsKey) withObject:value];
        return;
    }
#pragma clang diagnostic pop
    
    
    //如果setter没有查找到,调用+ (BOOL)accessInstanceVariablesDirectly方法,看该函数的返回值(没有重写,默认返回YES),如果是YES,可以直接访问实例变量,对实例变量设置值。实例变量访问优先级是:_key、_isKey、key、isKey
    if ([self.class accessInstanceVariablesDirectly]) {
        NSString *_key = [NSString stringWithFormat:@"_%@",key];
        NSString *_isKey = [NSString stringWithFormat:@"_is%@",capitalizedString];
        NSString *isKey = [NSString stringWithFormat:@"is%@",capitalizedString];
        
        NSString *tempKey;
        //查找所有的实例变量
        NSArray *ivarlist = [self getAllIvarList];
        if ([ivarlist containsObject:_key]) {
            tempKey = _key;
        } else if ([ivarlist containsObject:_isKey]) {
            tempKey = _isKey;
        } else if ([ivarlist containsObject:key]) {
            tempKey = key;
        } else if ([ivarlist containsObject:isKey]) {
            tempKey = isKey;
        }
        
        if (tempKey && tempKey.length > 0) {
            Ivar ivar = class_getInstanceVariable(self.class, tempKey.UTF8String);
            if (ivar) {
                object_setIvar(self, ivar, value);
            }
            return;
        }
        
    }
    
    //如果(BOOL)accessInstanceVariablesDirectly方法返回NO,或者实例变量没有找到一个与key对应的,会调用setValue:forUndefinedKey:方法。如果子类重写了该方法,调用该方法交由子类处理,不会抛出异常,否则抛出异常“该类不符合键值编码规范”
    [self setValue:value forUndefinedKey:key];
}

- (void)setCWValue:(id)value forKeyPath:(NSString *)keyPath
{
    NSArray *keyPaths = [keyPath componentsSeparatedByString:@"."];
    
    if (!keyPaths || keyPaths.count < 1 || !value) {
        return;
    }
    
    NSArray *ivarList = [self getAllIvarList];
    NSString *path = [NSString stringWithFormat:@"_%@",keyPaths.firstObject];
    if ([ivarList containsObject:path]) {
        id pathObject = object_getIvar(self, class_getInstanceVariable(self.class, path.UTF8String));
        [((NSObject *)pathObject) setCWValue:value forKey:keyPaths.lastObject];
    }
}

模拟KVC取值

-(id)valueCWForKey:(NSString *)key
{
    //1.查找getter方法:getKey、key、isKey、_getKey、_key
    NSString *capitalizedString = key.capitalizedString;
    NSString *getKey = [NSString stringWithFormat:@"get%@",capitalizedString];
    NSString *isKey = [NSString stringWithFormat:@"is%@",capitalizedString];
    NSString *_getKey = [NSString stringWithFormat:@"_get%@",capitalizedString];
    NSString *_key = [NSString stringWithFormat:@"_%@",key];
    SEL tempSel = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    if ([self respondsToSelector:NSSelectorFromString(getKey)]) {
        tempSel = NSSelectorFromString(getKey);
    } else if ([self respondsToSelector:NSSelectorFromString(key)]) {
        tempSel = NSSelectorFromString(key);
    } else if ([self respondsToSelector:NSSelectorFromString(isKey)]) {
        tempSel = NSSelectorFromString(isKey);
    } else if ([self respondsToSelector:NSSelectorFromString(_getKey)]) {
        tempSel = NSSelectorFromString(_getKey);
    } else if ([self respondsToSelector:NSSelectorFromString(_key)]) {
        tempSel = NSSelectorFromString(_key);
    }
    
    if (tempSel) {
        return [self performSelector:tempSel];
    }
    

    //2.没有找到getter方法,继续查找遵循某些命名约定的相关方法。
    /*2.1查重是否有countOfKey的方法,如果有,继续查找是否有objectInKeyAtIndex:/nameAtIndexes:方法,
     如果有,则返回一个响应所有NSArray方法的集合代理对象*/
    //2.2查重是否有countOfKey的方法,如果有,继续查找是否有enumeratorOfKey:/memberOfKey:方法,如果有,则返回一个响应所有NSSet方法的集合代理对象
    NSString *countOfKey = [NSString stringWithFormat:@"countOf%@",capitalizedString];
    NSString *objectInKeyAtIndex = [NSString stringWithFormat:@"objectIn%@AtIndex:",capitalizedString];
    NSString *nameAtIndexes = [NSString stringWithFormat:@"%@AtIndexes:",key];
    if ([self respondsToSelector:NSSelectorFromString(countOfKey)]) {
        
        int count = (int)[self performSelector:NSSelectorFromString(countOfKey)];
        int fuc = 0;
        //是否满足返回响应NSArray集合代理方法的对象
        if ([self respondsToSelector:NSSelectorFromString(objectInKeyAtIndex)]) {
            fuc = 1;
        } else if ([self respondsToSelector:NSSelectorFromString(nameAtIndexes)]) {
            fuc = 2;
        }
        
        if (fuc != 0) {
            NSMutableArray *array = NSMutableArray.array;
            id objc = nil;
            for (int i = 0; i < count; i++) {
                if (fuc == 1) {
                    objc = [self performSelector:NSSelectorFromString(objectInKeyAtIndex) withObject:[NSNumber numberWithInt:i]];
                } else {
                    NSArray *objectInexes = [self performSelector:NSSelectorFromString(nameAtIndexes)];
                    objc = objectInexes.firstObject;
                }
                
                if (objc) {
                    [array addObject:objc];
                }
            }
            
            return array;
        }
        
        //是否满足返回响应NSArray集合代理方法的对象及value的类型转换暂不提供
        //TODO
    }
    
    //3 以上都没有找到,调用+ (BOOL)accessInstanceVariablesDirectly方法,看该函数的返回值(没有重写,默认返回YES),如果是YES,可以直接访问实例变量,对实例变量设置值。实例变量访问优先级是:_key、_isKey、key、isKey
    if ([self.class accessInstanceVariablesDirectly]) {
        NSString *_key = [NSString stringWithFormat:@"_%@",key];
        NSString *_isKey = [NSString stringWithFormat:@"_is%@",capitalizedString];
        NSString *isKey = [NSString stringWithFormat:@"is%@",capitalizedString];
        
        NSString *tempKey;
        //查找所有的实例变量
        NSArray *ivarlist = [self getAllIvarList];
        if ([ivarlist containsObject:_key]) {
            tempKey = _key;
        } else if ([ivarlist containsObject:_isKey]) {
            tempKey = _isKey;
        } else if ([ivarlist containsObject:key]) {
            tempKey = key;
        } else if ([ivarlist containsObject:isKey]) {
            tempKey = isKey;
        }
        
        if (tempKey && tempKey.length > 0) {
            Ivar ivar = class_getInstanceVariable(self.class, tempKey.UTF8String);
            if (ivar) {
                return object_getIvar(self, ivar);
            }
        }
        
    }
#pragma clang diagnostic pop
    
    //4 如果(BOOL)accessInstanceVariablesDirectly方法返回NO,或者没有找相关的处理方法,会调用valueForUndefinedKey:方法。如果子类重写了该方法,调用该方法交由子类处理,不会抛出异常,否则抛出异常“该类不符合键值编码规范”
    //注意⚠️:如果数据是基本数据类型,转换为NSNumber,否则,转换为NSValue
    return [self valueForUndefinedKey:key];
}

- (id)valueCWForKeyPath:(NSString *)keyPath
{
    NSArray *keyPaths = [keyPath componentsSeparatedByString:@"."];
    
    if (!keyPaths || keyPaths.count < 1) {
        return nil;
    }
    
    NSArray *ivarList = [self getAllIvarList];
    NSString *path = [NSString stringWithFormat:@"_%@",keyPaths.firstObject];
    if ([ivarList containsObject:path]) {
        id pathObject = object_getIvar(self, class_getInstanceVariable(self.class, path.UTF8String));
        return [((NSObject *)pathObject) valueCWForKey:keyPaths.lastObject];
    }
    
    return nil;
}

//获取对象所有实例

- (NSArray *)getAllIvarList
{
    Class cls = self.class;
    NSMutableArray *array = NSMutableArray.array;
    while (cls && !([NSStringFromClass(cls) isEqualToString:@"NSObject"] || [NSStringFromClass(cls) hasPrefix:@"UI"])) {
        unsigned int count;
        Ivar *ivars = class_copyIvarList(cls, &count);
        
        for (int i = 0; i < count; i++) {
            Ivar inst = ivars[i];
            NSString *name = [NSString stringWithCString:ivar_getName(inst) encoding:NSUTF8StringEncoding];
            if (name) {
                [array addObject:name];
            }
        }
        
        free(ivars);
        cls = class_getSuperclass(cls);
    }
    
    return array;
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容

  • 一、KVC 很简单 KVC 很简单,每个人都会用,仅有的 API 如下:1、setValue: forKeyPat...
    CoderHG阅读 743评论 0 3
  • KVC称为:Key Value coding , 键值编码, 键值编码:由NSKeyValueCoding 非正...
    ChenL阅读 330评论 0 0
  • iOS 的KVC技术比较常用,可在运行时动态地对一个对象的属性赋值,并且如果该key是有添加KVO监听, 也会触...
    Sweet丶阅读 299评论 0 0
  • KVC(Key-value coding)键值编码,就是指iOS的开发中,可以允许开发者通过Key名直接访问对象的...
    奋斗的郅博阅读 163评论 0 0
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 8,536评论 28 53