1. 簡介
KVC 即鍵值編碼,KVC 是由 NSKeyValueCoding 非正式協(xié)議啟用的一種機(jī)制,對(duì)象采用該協(xié)議來間接訪問其屬性。即可以通過一個(gè)字符串key來訪問某個(gè)屬性,這種間接訪問機(jī)制補(bǔ)充了實(shí)例變量及其相關(guān)的訪問器方法所提供的直接訪問。
2. 相關(guān) API
主要有下面 4 個(gè)常用的方法:
- 通過
key設(shè)值/取值
//直接通過Key來取值
- (nullable id)valueForKey:(NSString *)key;
//通過Key來設(shè)值
- (void)setValue:(nullable id)value forKey:(NSString *)key;
- 通過
keyPath設(shè)值/取值
//通過KeyPath來取值
- (nullable id)valueForKeyPath:(NSString *)keyPath;
//通過KeyPath來設(shè)值
- (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath;
還有其他的一些方法:
//默認(rèn)返回YES,表示如果沒有找到Set<Key>方法的話,會(huì)按照_key,_iskey,key,iskey的順序搜索成員,設(shè)置成NO就不這樣搜索
+ (BOOL)accessInstanceVariablesDirectly;
//KVC提供屬性值正確性驗(yàn)證的API,它可以用來檢查set的值是否正確、為不正確的值做一個(gè)替換值或者拒絕設(shè)置新值并返回錯(cuò)誤原因。
- (BOOL)validateValue:(inout id __nullable * __nonnull)ioValue forKey:(NSString *)inKey error:(out NSError **)outError;
//這是集合操作的API,里面還有一系列這樣的API,如果屬性是一個(gè)NSMutableArray,那么可以用這個(gè)方法來返回。
- (NSMutableArray *)mutableArrayValueForKey:(NSString *)key;
//如果Key不存在,且KVC無法搜索到任何和Key有關(guān)的字段或者屬性,則會(huì)調(diào)用這個(gè)方法,默認(rèn)是拋出異常。
- (nullable id)valueForUndefinedKey:(NSString *)key;
//和上一個(gè)方法一樣,但這個(gè)方法是設(shè)值。
- (void)setValue:(nullable id)value forUndefinedKey:(NSString *)key;
//如果你在SetValue方法時(shí)面給Value傳nil,則會(huì)調(diào)用這個(gè)方法
- (void)setNilValueForKey:(NSString *)key;
//輸入一組key,返回該組key對(duì)應(yīng)的Value,再轉(zhuǎn)成字典返回,用于將Model轉(zhuǎn)到字典。
- (NSDictionary<NSString *, id> *)dictionaryWithValuesForKeys:(NSArray<NSString *> *)keys;
3. 底層原理
3.1 KVC 賦值底層原理
在日常開發(fā)中,針對(duì)對(duì)象屬性的賦值,一般有以下兩種方式:
- 通過
setter方法賦值 - 通過
KVC 鍵值編碼的相關(guān)API賦值
Person *person = [[Person alloc] init];
// 1、一般setter 方法
person.name = @"哈哈";
// 2、KVC方式
[person setValue:@"嘻嘻" forKey:@"name"];
下面針對(duì)使用最多的KVC設(shè)值方法:setValue:forKey,來進(jìn)行其底層原理的探索。
在這里,我們通過Key-Value Coding Programming Guide蘋果官方文檔來研究,針對(duì)設(shè)值流程,有以下說明:
當(dāng)調(diào)用 setValue:forKey:設(shè)值屬性 value 時(shí),其底層的執(zhí)行流程為:
[第一步]
首先查找是否有這三種setter 方法,并且查找順序?yàn)?code>set<Key>: -> _set<Key> -> setIs<Key>
- 如果實(shí)現(xiàn)了其中任意一個(gè)
setter方法,則直接設(shè)置成員變量的value( 注意:key是指成員變量名,首字母大小寫需要符合KVC的命名規(guī)范) - 如果沒有,則進(jìn)入下一步
[第二步]
如果沒有第一步中的三個(gè)簡單的 setter 方法,則查找accessInstanceVariablesDirectly是否返回YES
- 如果返回
YES,則查找間接訪問的實(shí)例變量進(jìn)行賦值,查找順序?yàn)?_<key> -> _is<Key> -> <key> -> is<Key>,如果找到其中任意一個(gè)實(shí)例變量,則賦值,如果都沒有,則進(jìn)入下一步 - 如果返回
NO,則進(jìn)入下一步
[第三步]
如果 setter 方法或者實(shí)例變量都沒有找到,系統(tǒng)會(huì)執(zhí)行該對(duì)象的setValue:forUndefinedKey:方法,默認(rèn)拋出NSUndefinedKeyException類型的異常。
注意:我們實(shí)現(xiàn)
setValue:forUndefinedKey:這個(gè)方法之后,哪怕沒有任何操作,也不會(huì)引發(fā)崩潰了。
綜上所述,KVC通過setValue:forKey:方法設(shè)值的流程以設(shè)置LGPerson的對(duì)象person的屬性name為例,如下圖所示:

3.2 KVC取值底層原理
同樣的,我們可以通過官方文檔分析KVC取值的底層原理
當(dāng)調(diào)用valueForKey:時(shí),其底層的執(zhí)行流程如下:
[第一步]
首先查找getter方法,按照get<Key> -> <key> -> is<Key> -> _<key>的方法順序查找
- 如果找到,則進(jìn)入
[第五步] - 如果沒找到,則進(jìn)入下一步
[第二步]
如果第一步中的getter方法沒有找到,KVC會(huì)查找countOf <Key>和objectIn <Key> AtIndex :和<key> AtIndexes :
- 如果找到
countOf<Key>和其他兩個(gè)方法中的任意一個(gè),則會(huì)創(chuàng)建一個(gè)響應(yīng)所有NSArray方法的集合代理對(duì)象,并返回該對(duì)象,即NSKeyValueArray,是NSArray的子類。代理對(duì)象隨后將接收到的所有NSArray消息轉(zhuǎn)換為countOf<Key>,objectIn<Key> AtIndex:和<key>AtIndexes:消息的某種組合,用來創(chuàng)建鍵值編碼對(duì)象。如果原始對(duì)象還實(shí)現(xiàn)了一個(gè)名為get<Key>:range:之類的可選方法,則代理對(duì)象也將在適當(dāng)時(shí)使用該方法(注意:方法名的命名規(guī)則要符合KVC的標(biāo)準(zhǔn)命名方法,包括方法簽名。) - 如果沒有找到這三個(gè)訪問數(shù)組的方法,則進(jìn)入下一步
[第三步]
如果沒有找到上面的幾種方法,則會(huì)同時(shí)查找countOf <Key>,enumeratorOf<Key>和memberOf<Key>這三個(gè)方法
- 如果這三個(gè)方法都找到,則會(huì)創(chuàng)建一個(gè)響應(yīng)所有
NSSet方法的集合代理對(duì)象,并返回該對(duì)象,此代理對(duì)象隨后將其收到的所有NSSet消息轉(zhuǎn)換為countOf<Key>,enumeratorOf<Key>和memberOf<Key>:消息的某種組合,用于創(chuàng)建它的對(duì)象 - 如果還是沒有找到,則進(jìn)入下一步
[第四步]
如果還沒有找到,檢查類方法accessInstanceVariablesDirectly是否YES,依次搜索_<key>,_is<Key>,<key>或is<Key>的實(shí)例變量
- 如果找到了,直接獲取
實(shí)例變量的值,進(jìn)入下一步 - 如果還沒找到,進(jìn)入[第六步]
[第五步]
根據(jù)搜索到的成員變量的值的類型,返回不同的結(jié)果:
- 如果是
對(duì)象指針,則直接返回結(jié)果 - 如果是
NSNumber支持的標(biāo)量類型,則將其存儲(chǔ)在NSNumber實(shí)例中并返回它 - 如果是是
NSNumber不支持的標(biāo)量類型,轉(zhuǎn)換為NSValue對(duì)象并返回該對(duì)象
[第六步]
如果上面5步的方法均失敗,系統(tǒng)會(huì)執(zhí)行該對(duì)象的valueForUndefinedKey:方法,默認(rèn)拋出NSUndefinedKeyException類型的異常
綜上所述,KVC通過 valueForKey:方法取值的流程以設(shè)置LGPerson的對(duì)象person的屬性name為例,如下圖所示:

4.自定義 KVC
原理:通過給 NSObject 添加分類CJLKVC,實(shí)現(xiàn)自定義的cjl_setValue:forKey:和cjl_valueForKey:方法,根據(jù)蘋果官方文檔提供的查找規(guī)則進(jìn)行實(shí)現(xiàn):
@interface NSObject (KVC)
//設(shè)值
- (void)customSetValue:(nullable id)value forKey:(NSString *)key;
//取值
- (nullable id)customValueForKey:(NSString *)key;
@end
4.1 自定義 KVC 設(shè)值
自定義KVC設(shè)置流程,主要分為以下幾個(gè)步驟:
- 1、判斷
key非空 - 2、查找
setter方法,順序是:setXXX、_setXXX、 setIsXXX - 3、判斷是否響應(yīng)
accessInstanceVariablesDirectly方法,即是否訪問實(shí)例變量,
返回YES,繼續(xù)下一步設(shè)值,
如果是NO,則崩潰 - 4、間接訪問變量賦值(只會(huì)走一次),順序是:
_key、_isKey、key、isKey- 4.1 定義一個(gè)收集實(shí)例變量的可變數(shù)組
- 4.2 通過
class_getInstanceVariable方法,獲取相應(yīng)的ivar - 4.3 通過
object_setIvar方法,對(duì)相應(yīng)的ivar設(shè)置值
- 5 、如果找不到相關(guān)實(shí)例變量,則拋出異常
//設(shè)值
- (void)customSetValue:(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 performSelectorWithMethodName:setKey value:value]) {
NSLog(@"*************%@*************", setKey);
return;
}else if([self performSelectorWithMethodName:_setKey value:value]){
NSLog(@"*************%@*************", _setKey);
return;
}else if([self performSelectorWithMethodName:setIsKey value:value]){
NSLog(@"*************%@*************", setIsKey);
return;
}
// 3、判斷是否響應(yīng)`accessInstanceVariablesDirectly`方法,即間接訪問實(shí)例變量,返回YES,繼續(xù)下一步設(shè)值,如果是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、間接訪問變量賦值,順序?yàn)椋篲key、_isKey、key、isKey
// 4.1 定義一個(gè)收集實(shí)例變量的可變數(shù)組
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 獲取相應(yīng)的 ivar
Ivar ivar = class_getInstanceVariable([self class], _key.UTF8String);
// 4.3 對(duì)相應(yīng)的 ivar 設(shè)置值
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];
}
4.2 自定義 KVC 取值
取值的自定義代碼如下,分為以下幾步
1、判斷key
非空2、查找相應(yīng)方法,順序是:
get<Key>、 <key>、 countOf<Key>、 objectIn<Key>AtIndex-
3、判斷是否能夠直接賦值實(shí)例變量,即判斷是否響應(yīng)
accessInstanceVariablesDirectly方法,間接訪問成員變量,返回
YES,繼續(xù)下一步取值如果是
NO,則崩潰 -
4、間接訪問實(shí)例變量,順序是:
_<key> _is<Key> <key> is<Key>4.1 定義一個(gè)收集實(shí)例變量的可變數(shù)組
4.2 通過
class_getInstanceVariable方法,獲取相應(yīng)的ivar4.3 通過
object_getIvar方法,返回相應(yīng)的ivar的值
//取值
- (nullable id)cjl_valueForKey:(NSString *)key{
// 1、判斷非空
if (key == nil || key.length == 0) {
return nil;
}
// 2、找到相關(guān)方法: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、判斷是否響應(yīng)`accessInstanceVariablesDirectly`方法,即間接訪問實(shí)例變量,返回YES,繼續(xù)下一步設(shè)值,如果是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.找相關(guān)實(shí)例變量進(jìn)行賦值,順序?yàn)椋篲<key>、 _is<Key>、 <key>、 is<Key>
// 4.1 定義一個(gè)收集實(shí)例變量的可變數(shù)組
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 @"";
}
5. 使用 keyPath
在日常開發(fā)中,一個(gè)類的成員變量有可能是自定義類或者其他的復(fù)雜數(shù)據(jù)類型,一般的操作是,我們可以先通過KVC獲取該屬性,然后再通過KVC獲取自定義類的屬性,就是比較麻煩,還有另一種比較簡便的方法,就是使用KeyPath,涉及以下兩個(gè)方法:setValue:forKeyPath: 和 valueForKeyPath:
//通過KeyPath來取值
- (nullable id)valueForKeyPath:(NSString *)keyPath;
//通過KeyPath來設(shè)值
- (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath;
比如以下的案例:
//Person類
@interface Person : NSObject
@property (nonatomic, copy) NSString *age;
@property (nonatomic, strong) Student *student;
@end
//Student類
@interface Student : NSObject
@property (nonatomic, copy) NSString *name;
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person = [[Person alloc] init];
Student *student = [Student alloc];
student.name = @"CJL";
person.student = student;
//根據(jù)kvc - keyPath路由修改student的subject屬性的值
[person setValue:@"嘻嘻" forKeyPath:@"student.name"];
NSLog(@"%@",[person valueForKeyPath:@"student.name"]);
}
return 0;
}
//*************打印結(jié)果*************
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] 改變后:嘻嘻
6.使用場(chǎng)景
6.1 動(dòng)態(tài)設(shè)值和取值
- 常用的可以通過
setValue:forKey:和valueForKey: - 也可以通過路由的方式
setValue:forKeyPath:和valueForKeyPath:
6.2 通過KVC訪問和修改私有變量
在日常開發(fā)中,對(duì)于類的私有屬性,在外部定義的對(duì)象,是無法直接訪問私有屬性的,但是對(duì)于KVC而言,一個(gè)對(duì)象沒有自己的隱私,所以可以通過KVC修改和訪問任何私有屬性,一般用于修改系統(tǒng)類的私有屬性。
6.3 多值操作(model和字典互轉(zhuǎn))
model和字典的轉(zhuǎn)換可以通過下面兩個(gè)KVC的API實(shí)現(xiàn):
//字典轉(zhuǎn)模型
- (void)setValuesForKeysWithDictionary:(NSDictionary<NSString *, id> *)keyedValues;
//模型轉(zhuǎn)字典
- (NSDictionary<NSString *, id> *)dictionaryWithValuesForKeys:(NSArray<NSString *> *)keys;
6.4 修改一些系統(tǒng)空間的內(nèi)部屬性
在日常開發(fā)中,我們知道,很多UI控件都是在其內(nèi)部由多個(gè)UI控件組合而成,這些內(nèi)部控件蘋果并沒有提供訪問的API,但是使用KVC可以解決這個(gè)問題,常用的就是自定義tabbar、個(gè)性化UITextField中的placeHolderText
6.5 用KVC實(shí)現(xiàn)高階消息傳遞
在對(duì)容器類使用KVC時(shí),valueForKey:將會(huì)被傳遞給容器中的每一個(gè)對(duì)象,而不是對(duì)容器本身進(jìn)行操作,結(jié)果會(huì)被添加到返回的容器中,這樣,可以很方便的操作集合 來返回 另一個(gè)集合。
//KVC實(shí)現(xiàn)高階消息傳遞
- (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);
}
}
//********打印結(jié)果********
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