KVC原理

一.KVC的setValue:forKey:底層執(zhí)行

1.優(yōu)先查找setter方法
先查找是否有setKey方法,如果沒有,查找是否有_setKey方法,如果還沒有找到,查找是否有setIsKey方法

2.setter方法沒有查找到,會調用 + (BOOL)accessInstanceVariablesDirectly方法,默認返回YES,表示可以直接通過實例變量設置值。
如果返回YES,會查找實例變量,不過,它有查找優(yōu)先級。先查找_key,沒有找到,會查找_isKey,若沒有找到,查找是否有key,如還沒有找到,會查找isKey。找到實例變量,給這個實例變量設置值,若最后還沒有找到,進入步驟3
如果返回NO,進入步驟3

3.以上都沒有找到,執(zhí)行 setValue:forUndefinedKey:方法
3.1 如果沒有重寫該方法,會調用系統(tǒng)的,并拋出異常
3.2 如果重寫了,執(zhí)行你重寫的這個方法,將這種情況交由你來處理,不會拋出異常,中斷程序。

KVC設值流程圖
KVC of setValue.jpeg

二.KVC的valueForKey:底層執(zhí)行

1.優(yōu)先查找getter方法
先查找getKey,沒有找到,查找key,如沒有找到,繼續(xù)查找isKey,以上還沒有找到,會先查找_getKey,再查找_key。找到了執(zhí)行該方法,并返回值。

2.查找響應集合NSArray所有方法的代理對象
先查找是否有countOfKey方法,若沒有,直接進入步驟5。如果有countOfKey方法,繼續(xù)查找是否有objectInKeyAtIndex:/ keyAtIndexes:方法,如果有,返回一個可以響應集合NSArray所有方法的代理對象(實際是一個NSKeyValueArray對象,它是NSArray的子類)。使用這個對象調用NSArray的所有方法,會轉換為調用countOfKey方法、objectInKeyAtIndex:/ keyAtIndexes:方法組合的形式來創(chuàng)建鍵值編碼對象。
注意:
1.如果objectInKeyAtIndex:、keyAtIndexes:方法都存在,調用objectAtIndex:方法,會觸發(fā)objectInKeyAtIndex:方法,調用objectsAtIndexes:方法,會觸發(fā)keyAtIndexes:方法。
2.如果只有objectInKeyAtIndex:方法,調用objectAtIndex:objectsAtIndexes:方法,都會觸發(fā)objectInKeyAtIndex:方法,只不過,調用objectsAtIndexes:方法返回的結果是空數(shù)組
3.如果只有keyAtIndexes:方法,調用objectAtIndex:objectsAtIndexes:方法,都會觸發(fā)keyAtIndexes:方法。

3.查找響應集合NSSet所有方法的代理對象
先查找是否有countOfKey方法,若沒有,直接進入步驟5。如果有countOfKey方法,繼續(xù)查找是否有enumeratorOfKey:/ memberOfKey:方法,如果有,返回一個可以響應集合NSSet所有方法的代理對象。使用這個對象調用NSSet的所有方法,會轉換為調用countOfKey方法、enumeratorOfKey:/ memberOfKey:方法組合的形式來創(chuàng)建鍵值編碼對象。

4.以上都沒有找到,調用+ (BOOL)accessInstanceVariablesDirectly方法,默認返回 YES,表示可以直接通過實例變量設置值。
如果返回YES,會查找實例變量,不過,它有查找優(yōu)先級。先查找_key,沒有找到,會查找_isKey,若沒有找到,查找是否有key,如還沒有找到,會查找isKey。找到實例變量,返回獲取到的值,若最后還沒有找到,進入步驟5
如果返回NO,進入步驟5

5.以上都沒有找到,執(zhí)行valueForUndefinedKey:方法
5.1 如果沒有重寫該方法,會調用系統(tǒng)的,并拋出異常
5.2 如果重寫了,執(zhí)行你重寫的這個方法,將這種情況交由你來處理,不會拋出異常,中斷程序。

KVC取值流程圖
KVC of valueForKey.jpeg

三、根據(jù)原理,自己實現(xiàn)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方法,看該函數(shù)的返回值(沒有重寫,默認返回YES),如果是YES,可以直接訪問實例變量,對實例變量設置值。實例變量訪問優(yōu)先級是:_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:方法。如果子類重寫了該方法,調用該方法交由子類處理,不會拋出異常,否則拋出異?!霸擃惒环湘I值編碼規(guī)范”
    [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方法,繼續(xù)查找遵循某些命名約定的相關方法。
    /*2.1查重是否有countOfKey的方法,如果有,繼續(xù)查找是否有objectInKeyAtIndex:/nameAtIndexes:方法,
     如果有,則返回一個響應所有NSArray方法的集合代理對象*/
    //2.2查重是否有countOfKey的方法,如果有,繼續(xù)查找是否有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方法,看該函數(shù)的返回值(沒有重寫,默認返回YES),如果是YES,可以直接訪問實例變量,對實例變量設置值。實例變量訪問優(yōu)先級是:_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:方法。如果子類重寫了該方法,調用該方法交由子類處理,不會拋出異常,否則拋出異?!霸擃惒环湘I值編碼規(guī)范”
    //注意??:如果數(shù)據(jù)是基本數(shù)據(jù)類型,轉換為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;
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 一、KVC 很簡單 KVC 很簡單,每個人都會用,僅有的 API 如下:1、setValue: forKeyPat...
    CoderHG閱讀 864評論 0 3
  • KVC稱為:Key Value coding , 鍵值編碼, 鍵值編碼:由NSKeyValueCoding 非正...
    ChenL閱讀 418評論 0 0
  • iOS 的KVC技術比較常用,可在運行時動態(tài)地對一個對象的屬性賦值,并且如果該key是有添加KVO監(jiān)聽, 也會觸...
    Sweet丶閱讀 376評論 0 0
  • KVC(Key-value coding)鍵值編碼,就是指iOS的開發(fā)中,可以允許開發(fā)者通過Key名直接訪問對象的...
    奮斗的郅博閱讀 216評論 0 0
  • 我是黑夜里大雨紛飛的人啊 1 “又到一年六月,有人笑有人哭,有人歡樂有人憂愁,有人驚喜有人失落,有的覺得收獲滿滿有...
    陌忘宇閱讀 8,834評論 28 54

友情鏈接更多精彩內容