iOS KVC 底層原理

KVC的全稱是Key-Value Coding,翻譯成中文是 鍵值編碼,鍵值編碼是由NSKeyValueCoding非正式協議啟用的一種機制,對象采用該協議來間接訪問其屬性。既可以通過一個·字符串key來訪問某個屬性·。這種間接訪問機制補充了實例變量及其相關的訪問器方法所提供的直接訪問。

KVC 相關API
常用方法

主要有以下四個常用的方法

通過key設值/取值

//直接通過Key來取值
- (nullable id)valueForKey:(NSString *)key;

//通過Key來設值
- (void)setValue:(nullable id)value forKey:(NSString *)key;
  • 通過keyPath (即路由)設值/取值
//通過KeyPath來取值
- (nullable id)valueForKeyPath:(NSString *)keyPath; 

//通過KeyPath來設值                 
- (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath;  

其他方法

//默認返回YES,表示如果沒有找到Set<Key>方法的話,會按照_key,_iskey,key,iskey的順序搜索成員,設置成NO就不這樣搜索
+ (BOOL)accessInstanceVariablesDirectly;

//KVC提供屬性值正確性驗證的API,它可以用來檢查set的值是否正確、為不正確的值做一個替換值或者拒絕設置新值并返回錯誤原因。
- (BOOL)validateValue:(inout id __nullable * __nonnull)ioValue forKey:(NSString *)inKey error:(out NSError **)outError;

//這是集合操作的API,里面還有一系列這樣的API,如果屬性是一個NSMutableArray,那么可以用這個方法來返回。
- (NSMutableArray *)mutableArrayValueForKey:(NSString *)key;

//如果Key不存在,且KVC無法搜索到任何和Key有關的字段或者屬性,則會調用這個方法,默認是拋出異常。
- (nullable id)valueForUndefinedKey:(NSString *)key;

//和上一個方法一樣,但這個方法是設值。
- (void)setValue:(nullable id)value forUndefinedKey:(NSString *)key;

//如果你在SetValue方法時面給Value傳nil,則會調用這個方法
- (void)setNilValueForKey:(NSString *)key;

//輸入一組key,返回該組key對應的Value,再轉成字典返回,用于將Model轉到字典。
- (NSDictionary<NSString *, id> *)dictionaryWithValuesForKeys:(NSArray<NSString *> *)keys;

KVC 設值 底層原理

在日常開發中,針對對象屬性的賦值,一般有以下兩種方式

  • 直接通過setter方法賦值
  • 通過KVC鍵值編碼的相關API賦值
LGPerson *person = [[LGPerson alloc] init];
// 1、一般setter 方法
person.name      = @"CJL_哈哈";
// 2、KVC方式
[person setValue:@"CJL_嘻嘻" forKey:@"name"]; 

下面針對使用最多的KVC設值方法:setValue:forKey,來進行其底層原理的探索。

首先進入setValue:forKey的聲明,發現是在Foundation框架中,而Foundation框架是不開源的,有以下幾種方式可以去探索底層

  • 通過Hopper反匯編,查看偽代碼
  • 通過蘋果官方文檔
  • Github搜索是否有相關的demo

在這里,我們通過Key-Value Coding Programming Guide蘋果官方文檔來研究,針對設值流程,有如下說明

當調用setValue:forKey:設置屬性value時,其底層的執行流程為

  • 【第一步】首先查找是否有這三種setter方法,按照查找順序為set<Key>:-> _set<Key> -> setIs<Key>

    • 如果有其中任意一個setter方法,則直接設置屬性的value(主注意:key是指成員變量名,首字符大小寫需要符合KVC的命名規范)

    • 如果都沒有,則進入【第二步】

  • 【第二步】:如果沒有第一步中的三個簡單的setter方法,則查找accessInstanceVariablesDirectly是否返回YES,

    • 如果返回YES,則查找間接訪問的實例變量進行賦值,查找順序為:_<key> -> _is<Key> -> <key> -> is<Key>

      • 如果找到其中任意一個實例變量,則賦值

      • 如果都沒有,則進入【第三步】

    • 如果返回NO,則進入【第三步】

  • 【第三步】如果setter方法 或者 實例變量都沒有找到,系統會執行該對象的setValue:forUndefinedKey:方法,默認拋出NSUndefinedKeyException類型的異常

綜上所述,KVC通過 setValue:forKey: 方法設值的流程以設置LGPerson的對象person的屬性name為例,如下圖所示

image

KVC 取值 底層原理

同樣的,我們可以通過官方文檔分析KVC取值的底層原理

當調用valueForKey:時,其底層的執行流程如下

  • 【第一步】首先查找getter方法,按照get<Key> -> <key> -> is<Key> -> _<key>的方法順序查找,

    • 如果找到,則進入【第五步】

    • 如果沒有找到,則進入【第二步】

  • 【第二步】如果第一步中的getter方法沒有找到,KVC會查找countOf <Key>和objectIn <Key> AtIndex :和<key> AtIndexes :

    • 如果找到countOf <Key>和其他兩個中的一個,則會創建一個響應所有NSArray方法的集合代理對象,并返回該對象,即NSKeyValueArray,是NSArray子類。代理對象隨后將接收到的所有NSArray消息轉換為countOf<Key>,objectIn<Key> AtIndex:和<key>AtIndexes:消息的某種組合,用來創建鍵值編碼對象。如果原始對象還實現了一個名為get<Key>:range:之類的可選方法,則代理對象也將在適當時使用該方法(注意:方法名的命名規則要符合KVC的標準命名方法,包括方法簽名。)

    • 如果沒有找到這三個訪問數組的,請繼續進入【第三步】

  • 【第三步】如果沒有找到上面的幾種方法,則會同時查找countOf <Key>,enumeratorOf<Key>和memberOf<Key>這三個方法

    • 如果這三個方法都找到,則會創建一個響應所有NSSet方法的集合代理對象,并返回該對象,此代理對象隨后將其收到的所有NSSet消息轉換為countOf<Key>,enumeratorOf<Key>和memberOf<Key>:消息的某種組合,用于創建它的對象

    • 如果還是沒有找到,則進入【第四步】

  • 【第四步】如果還沒有找到,檢查類方法InstanceVariablesDirectly是否YES,依次搜索_<key>,_is<Key>,<key>或is<Key>的實例變量

    • 如果搜到,直接獲取實例變量的值,進入【第五步】
  • 【第五步】根據搜索到的屬性值的類型,返回不同的結果

    • 如果是對象指針,則直接返回結果

    • 如果是NSNumber支持的標量類型,則將其存儲在NSNumber實例中并返回它

    • 如果是是NSNumber不支持的標量類型,請轉換為NSValue對象并返回該對象

  • 【第六步】如果上面5步的方法均失敗,系統會執行該對象的valueForUndefinedKey:方法,默認拋出NSUndefinedKeyException類型的異常

綜上所述,KVC通過 valueForKey: 方法取值的流程以設置LGPerson的對象person的屬性name為例,如下圖所示

&

自定義KVC

原理:通過給NSObject添加分類CJLKVC,實現自定義的cjl_setValue:forKey:cjl_valueForKey:方法,根據蘋果官方文檔提供的查找規則進行實現

@interface NSObject (CJLKVC)

//設值
- (void)cjl_setValue:(nullable id)value forKey:(NSString *)key;
//取值
- (nullable id)cjl_valueForKey:(NSString *)key;

@end

自定義KVC設值

自定義KVC設置流程,主要分為以下幾個步驟:

  • 1、判斷key非空
  • 2、查找setter方法,順序是:setXXX、_setXXX、 setIsXXX
  • 3、判斷是否響應accessInstanceVariablesDirectly方法,即間接訪問實例變量,
    • 返回YES,繼續下一步設值,
    • 如果是NO,則崩潰
  • 4、間接訪問變量賦值(只會走一次),順序是:_key、_isKey、key、isKey
    • 4.1 定義一個收集實例變量的可變數組
    • 4.2 通過class_getInstanceVariable方法,獲取相應的 ivar
    • 4.3 通過object_setIvar方法,對相應的 ivar 設置值
  • 5、如果找不到相關實例變量,則拋出異常
//設值
- (void)cjl_setValue:(nullable id)value forKey:(NSString *)key{

//    1、判斷key 是否存在
    if (key == nil || key.length == 0) return;

//    2、找setter方法,順序是:setXXX、_setXXX、 setIsXXX
    // key 要大寫
    NSString *Key = key.capitalizedString;
    // key 要大寫
    NSString *setKey = [NSString stringWithFormat:@"set%@:", Key];
    NSString *_setKey = [NSString stringWithFormat:@"_set%@:", Key];
    NSString *setIsKey = [NSString stringWithFormat:@"setIs%@:", Key];

    if ([self cjl_performSelectorWithMethodName:setKey value:value]) {
        NSLog(@"*************%@*************", setKey);
        return;
    }else if([self cjl_performSelectorWithMethodName:_setKey value:value]){
        NSLog(@"*************%@*************", _setKey);
        return;
    }else if([self cjl_performSelectorWithMethodName:setIsKey value:value]){
        NSLog(@"*************%@*************", setIsKey);
        return;
    }

//    3、判斷是否響應`accessInstanceVariablesDirectly`方法,即間接訪問實例變量,返回YES,繼續下一步設值,如果是NO,則崩潰
    if (![self.class accessInstanceVariablesDirectly]) {
        @throw [NSException exceptionWithName:@"CJLUnKnownKeyException" reason:[NSString stringWithFormat:@"****[%@ valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.****",self] userInfo:nil];
    }

//    4、間接訪問變量賦值,順序為:_key、_isKey、key、isKey
    // 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:@"CJLUnknownKeyException" reason:[NSString stringWithFormat:@"****[%@ %@]: this class is not key value coding-compliant for the key name.****",self,NSStringFromSelector(_cmd)] userInfo:nil];

}

自定義KVC取值

取值的自定義代碼如下,分為以下幾步

  • 1、判斷key非空

  • 2、查找相應方法,順序是:get<Key>、 <key>、 countOf<Key>、 objectIn<Key>AtIndex

  • 3、判斷是否能夠直接賦值實例變量,即判斷是否響應accessInstanceVariablesDirectly方法,間接訪問實例變量,

    • 返回YES,繼續下一步取值

    • 如果是NO,則崩潰

  • 4、間接訪問實例變量,順序是:_<key> _is<Key> <key> is<Key>

    • 4.1 定義一個收集實例變量的可變數組

    • 4.2 通過class_getInstanceVariable方法,獲取相應的 ivar

    • 4.3 通過object_getIvar方法,返回相應的 ivar 的值

//取值
- (nullable id)cjl_valueForKey:(NSString *)key{

//    1、判斷非空
    if (key == nil || key.length == 0) {
        return nil;
    }

//    2、找到相關方法:get<Key> <key> countOf<Key>  objectIn<Key>AtIndex
    // key 要大寫
    NSString *Key = key.capitalizedString;
    // 拼接方法
    NSString *getKey = [NSString stringWithFormat:@"get%@",Key];
    NSString *countOfKey = [NSString stringWithFormat:@"countOf%@",Key];
    NSString *objectInKeyAtIndex = [NSString stringWithFormat:@"objectIn%@AtIndex:",Key];

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    if ([self respondsToSelector:NSSelectorFromString(getKey)]) {
        return [self performSelector:NSSelectorFromString(getKey)];
    }else if ([self respondsToSelector:NSSelectorFromString(key)]){
        return [self performSelector:NSSelectorFromString(key)];
    }
    //集合類型
    else if ([self respondsToSelector:NSSelectorFromString(countOfKey)]){
        if ([self respondsToSelector:NSSelectorFromString(objectInKeyAtIndex)]) {
            int num = (int)[self performSelector:NSSelectorFromString(countOfKey)];
            NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:1];
            for (int i = 0; i<num-1; i++) {
                num = (int)[self performSelector:NSSelectorFromString(countOfKey)];
            }
            for (int j = 0; j<num; j++) {
                id objc = [self performSelector:NSSelectorFromString(objectInKeyAtIndex) withObject:@(num)];
                [mArray addObject:objc];
            }
            return mArray;
        }
    }

#pragma clang diagnostic pop

//    3、判斷是否響應`accessInstanceVariablesDirectly`方法,即間接訪問實例變量,返回YES,繼續下一步設值,如果是NO,則崩潰
    if (![self.class accessInstanceVariablesDirectly]) {
        @throw [NSException exceptionWithName:@"CJLUnKnownKeyException" reason:[NSString stringWithFormat:@"****[%@ valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.****",self] userInfo:nil];
    }

//    4.找相關實例變量進行賦值,順序為:_<key>、 _is<Key>、 <key>、 is<Key>
    // 4.1 定義一個收集實例變量的可變數組
    NSMutableArray *mArray = [self getIvarListName];
    // 例如:_name -> _isName -> name -> isName
    NSString *_key = [NSString stringWithFormat:@"_%@",key];
    NSString *_isKey = [NSString stringWithFormat:@"_is%@",Key];
    NSString *isKey = [NSString stringWithFormat:@"is%@",Key];
    if ([mArray containsObject:_key]) {
        Ivar ivar = class_getInstanceVariable([self class], _key.UTF8String);
        return object_getIvar(self, ivar);;
    }else if ([mArray containsObject:_isKey]) {
        Ivar ivar = class_getInstanceVariable([self class], _isKey.UTF8String);
        return object_getIvar(self, ivar);;
    }else if ([mArray containsObject:key]) {
        Ivar ivar = class_getInstanceVariable([self class], key.UTF8String);
        return object_getIvar(self, ivar);;
    }else if ([mArray containsObject:isKey]) {
        Ivar ivar = class_getInstanceVariable([self class], isKey.UTF8String);
        return object_getIvar(self, ivar);;
    }

    return @"";

    return @"";
}

使用路由訪問,即keyPath

在日常開發中,一個類的成員變量有可能是自定義類或者其他的復雜數據類型,一般的操作是,我們可以先通過KVC獲取該屬性,然后再通過KVC獲取自定義類的屬性,就是比較麻煩,還有另一種比較簡便的方法,就是使用KeyPath路由,涉及以下兩個方法:setValue:forKeyPath:valueForKeyPath:

//通過KeyPath來取值
- (nullable id)valueForKeyPath:(NSString *)keyPath;                  

//通過KeyPath來設值
- (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath;

參考如下的案例

//CJLPerson類
@interface CJLPerson : NSObject
@property (nonatomic, copy)   NSString          *age;
@property (nonatomic, strong) CJLStudent         *student;
@end

//CJLStudent類
@interface CJLStudent : NSObject
@property (nonatomic, copy)   NSString          *name;
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        CJLPerson *person = [[CJLPerson alloc] init];
        CJLStudent *student = [CJLStudent alloc];
        student.name    = @"CJL";
        person.student     = student;
        //根據kvc - keyPath路由修改student的subject屬性的值
        [person setValue:@"嘻嘻" forKeyPath:@"student.name"];
        NSLog(@"%@",[person valueForKeyPath:@"student.name"]);
    }
    return 0;
}

//*************打印結果*************
2020-10-27 09:55:08.512833+0800 001-KVC簡介[58089:6301894] 改變前:CJL
2020-10-27 09:55:08.512929+0800 001-KVC簡介[58089:6301894] 改變后:嘻嘻

KVC 使用場景

1、動態設值和取值

  • 常用的可以通過setValue:forKey:valueForKey:

  • 也可以通過路由的方式setValue:forKeyPath:valueForKeyPath:

2、通過KVC訪問和修改私有變量

在日常開發中,對于類的私有屬性,在外部定義的對象,是無法直接訪問私有屬性的,但是對于KVC而言,一個對象沒有自己的隱私,所以可以通過KVC修改和訪問任何私有屬性

3、多值操作(model和字典互轉)

model和字典的轉換可以通過下面兩個KVC的API實現

//字典轉模型
- (void)setValuesForKeysWithDictionary:(NSDictionary<NSString *, id> *)keyedValues;

//模型轉字典
- (NSDictionary<NSString *, id> *)dictionaryWithValuesForKeys:(NSArray<NSString *> *)keys;

4、修改一些系統空間的內部屬性

在日常開發中,我們知道,很多UI控件都是在其內部由多個UI空間組合而成,這些內部控件蘋果并沒有提供訪問的API,但是使用KVC可以解決這個問題,常用的就是自定義tabbar、個性化UITextField中的placeHolderText

5、用KVC實現高階消息傳遞

在對容器類使用KVC時,valueForKey:將會被傳遞給容器中的每一個對象,而不是對容器本身進行操作,結果會被添加到返回的容器中,這樣,可以很方便的操作集合 來返回 另一個集合

如下所示

//KVC實現高階消息傳遞
- (void)transmitMsg{
    NSArray *arrStr = @[@"english", @"franch", @"chinese"];
    NSArray *arrCapStr = [arrStr valueForKey:@"capitalizedString"];

    for (NSString *str in arrCapStr) {
        NSLog(@"%@", str);
    }

    NSArray *arrCapStrLength = [arrCapStr valueForKeyPath:@"capitalizedString.length"];
    for (NSNumber *length in arrCapStrLength) {
        NSLog(@"%ld", (long)length.integerValue);
    }
}

//********打印結果********
2020-10-27 11:33:43.377672+0800 CJLCustom[60035:6380757] English
2020-10-27 11:33:43.377773+0800 CJLCustom[60035:6380757] Franch
2020-10-27 11:33:43.377860+0800 CJLCustom[60035:6380757] Chinese
2020-10-27 11:33:43.378233+0800 CJLCustom[60035:6380757] 7
2020-10-27 11:33:43.378327+0800 CJLCustom[60035:6380757] 6
2020-10-27 11:33:43.378417+0800 CJLCustom[60035:6380757] 7

附錄

自定義KVC的完整代碼見Github-CustomKVC_KVO,喜歡的可以點個?

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容