
1.KVC協議定義
鍵值編碼是由NSKeyValueCoding非正式協議啟用的一種機制,物件采用該機制來提供對其屬性的間接訪問,當物件符合鍵值編碼時,其屬性可通過字串引數通過簡潔、統一的訊息傳遞介面進行尋址,這種間接訪問機制補充了實體變數及其相關訪問器方法提供的直接訪問,
-
KVC在Objective-C中的定義
KVC的定義都是對NSObject的擴展來實作的(Objective-C中有個顯式的NSKeyValueCoding類別名-分類),查看setValueForKey方法,發現其在Foundation里面,而Foundation框架是不開源的,只能在蘋果官方檔案查找,見下圖:
所有程式都是單一行程運行,行程之間相互獨立,
作為一個開發者,有一個學習的氛圍跟一個交流圈子特別重要,這是一個我的iOS交流群:834688868,不管你是大牛還是小白都歡迎入駐 ,分享BAT,阿里面試題、面試經驗,討論技術, 大家一起交流學習成長!
如果你正在面試,或者正準備跳槽,不妨看看我精心總結的面試資料: BAT 大廠最新面試題+答案合集(持續更新中) 來獲取一份詳細的大廠面試資料 為你的跳槽加薪多一份保障
2.KVC提供的API方法
-
我們可以學習解讀蘋果的官方檔案,對
KVC有更深的理解,Key-Value Coding Programming Guide
蘋果對一些容器類比如
NSArray或者NSSet等,KVC有著特殊的實作, -
常用方法
對于所有繼承了
NSObject的型別,也就是幾乎所有的Objective-C物件都能使用KVC,下面是KVC最為重要的四個方法:- (nullable id)valueForKey:(NSString *)key; // 直接通過Key來取值 - (void)setValue:(nullable id)value forKey:(NSString *)key; // 通過Key來設值 - (nullable id)valueForKeyPath:(NSString *)keyPath; // 通過KeyPath來取值 - (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath; // 通過KeyPath來設值 -
特殊方法
當然
NSKeyValueCoding類別中還有其他的一些方法,這些方法在碰到特殊情況或者有特殊需求還是會用到的,// 默認回傳YES,表示如果沒有找到Set方法的話,會按照_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在進行結構體處理時,需要用到NSValue,設值時,將結構體封裝成NSValue,進行鍵值設值;取值同樣回傳NSValue,然后按照結構體格式進行決議,見下面代碼:// 結構體 ThreeFloats floats = {1.,2.,3.}; // 封裝成NSValue NSValue *value = [NSValue valueWithBytes:&floats objCType:@encode(ThreeFloats)]; // 設值 [person setValue:value forKey:@"threeFloats"]; // 取值 NSValue *value1 = [person valueForKey:@"threeFloats"]; // 結構體決議 ThreeFloats th; [value1 getValue:&th]; NSLog(@"%f-%f-%f",th.x,th.y,th.z); -
字典處理(模型轉換)
字典可以實作與模型進行裝換,也可以通過鍵值陣列從模型中獲取字典資料,見下面代碼:
- (void)dictionaryTest{ // 字典 NSDictionary* dict = @{ @"name":@"Cooci", @"nick":@"KC", @"subject":@"iOS", @"age":@18, @"length":@180 }; // 模型 LGStudent *p = [[LGStudent alloc] init]; // 字典轉模型 [p setValuesForKeysWithDictionary:dict]; // 鍵值陣列 NSArray *array = @[@"name",@"age"]; // 從模型中獲取回應的字典資料 NSDictionary *dic = [p dictionaryWithValuesForKeys:array]; NSLog(@"%@",dic); }
3.KVC設值取值順序
KVC是怎么使用的,我們都很清楚,那么KVC在內部是按什么樣的順序來尋找key的呢?這是我們要探索的重點,
1.設值
當呼叫setValue:forKey:代碼時,底層的執行機制是怎樣的呢?在官方檔案中有相關的說明,見下圖:

-
翻譯過來的意思是:
setValue:forKey:的默認實作,給定key和value引數作為輸入,嘗試將名為key的屬性設定為value,在接收呼叫的物件內部,使用以下程序:按順序查找名為set<Key>:或_set<Key>的第一個訪問器, 如果找到,則使用輸入值(或根據需要展開的值)呼叫它并完成,如果未找到簡單訪問器,并且類方法accessInstanceVariablesDirectly回傳YES,則按順序查找名稱類似于_<key>、_is<Key>、<key>或is<Key>的實體變數, 如果找到,直接使用輸入值(或解包值)設定變數并完成, 在未找到訪問器或實體變數時,呼叫setValue:forUndefinedKey:, 默認情況下,這會引發例外,但NSObject的子類可能會提供特定于鍵的行為, -
根據上的官方內容,可以得出如下實作機制:
- 按順序查找名為
set<Key>,_set<Key>或者setIs<Key>的setter訪問器順序查找,如果找到就呼叫它 - 只要實作任意一個,那么就會將呼叫這個方法,將屬性的值設為傳進來的值
- 如果沒有找到這些
setter方法,KVC機制會檢查+ (BOOL)accessInstanceVariablesDirectly方法有沒有回傳YES,默認該方法會回傳YES,如果重寫了該方法讓其回傳NO的話,那么在這一步KVC會執行setValue:forUndefinedKey:方法; - 如果回傳
YES,KVC機制會優先搜索該類里面有沒有名為_<Key>的成員變數,無論該變數是在類介面處定義,還是在類實作處定義,也無論用了什么樣的訪問修飾符,只在存在以_<Key>命名的變數,KVC都可以對該成員變數賦值 KVC機制再會繼續搜索_is<Key>、<key>和is<key>的成員變數,再給它們賦值- 如果上面列出的方法或者成員變數都不存在,系統將會執行該物件的
setValue:forUndefinedKey:方法,默認是拋出例外,
- 按順序查找名為
-
以
[person setValue:@"newName" forKey:@"name"];為例,可以得出以下結論:- 優先通過
setter方法,進行屬性設定,呼叫順序是:setName_setNamesetIsName
- 如果以上方法均未找到,并且
accessInstanceVariablesDirectly回傳YES,則通過成員變數進行設定,順序是:_name_isNamenameisName
可通過案例進行驗證,這里不再展示,
- 優先通過
-
accessInstanceVariablesDirectly說明重寫
+ (BOOL)accessInstanceVariablesDirectly方法讓其回傳NO,這樣的話,如果KVC沒有找到set<Key>、_set<Key>、setIs<Key>相關方法時,會直接用setValue:forUndefinedKey:方法,我們用代碼來測驗一下上面的KVC機制:@interface LGPerson : NSObject { @public NSString *_isName; NSString *name; NSString *isName; NSString *_name; } @end @implementation LGPerson +(BOOL)accessInstanceVariablesDirectly{ return NO; } -(id)valueForUndefinedKey:(NSString *)key{ NSLog(@"出現例外,該key不存在%@",key); return nil; } -(void)setValue:(id)value forUndefinedKey:(NSString *)key{ NSLog(@"出現例外,該key不存在%@",key); } // 設定方法全部注釋掉 // -(void)setName:(NSString*)name{ // toSetName = name; // } // - (void)_setName:(NSString *)name{ // NSLog(@"%s - %@",__func__,name); // } // - (void)setIsName:(NSString *)name{ // NSLog(@"%s - %@",__func__,name); // } @end int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... LGPerson* person = [LGPerson new]; [person setValue:@"NewName" forKey:@"name"]; NSString* name = [person valueForKey:@"name"]; NSLog(@"value for key : %@",name); NSLog(@"取值_name:%@",person->_name); NSLog(@"取值_isName:%@",person->_isName); NSLog(@"取值name:%@",person->name); NSLog(@"取值isName:%@",person->isName); } return 0; }運行結構見下圖:

這說明了重寫
+(BOOL)accessInstanceVariablesDirectly方法讓其回傳NO后,KVC找不到set<Key>等方法后,不再去找<Key>系列成員變數,而是直接呼叫setValue:forUndefinedKey:方法,所以開發者如果不想讓自己的類實作KVC,就可以這么做, -
KVC設值流程圖

2.取值
當呼叫valueForKey:的代碼時,底層的執行機制又是怎樣的呢?在官方檔案中有相關的說明,見下圖:

-
根據上的官方內容,翻譯之后可以得出如下實作機制:
- 首先按
get<Key>,<Key>,is<Key>,_<Key>的順序方法查找getter方法,找到的話會直接呼叫,如果是BOOL或者Int等值型別, 會將其包裝成一個NSNumber物件, - 如果上面的
getter沒有找到,KVC則會查找countOf<Key>,objectIn<Key>AtIndex或<Key>AtIndexes格式的方法,如果countOf<Key>方法和另外兩個方法中的一個被找到,那么就會回傳一個可以回應NSArray所有方法的代理集合(它是NSKeyValueArray,是NSArray的子類),呼叫這個代理集合的方法,或者說給這個代理集合發送屬于NSArray的方法,就會以countOf<Key>,objectIn<Key>AtIndex或At<Key>Indexes這幾個方法組合的形式呼叫,還有一個可選的get<Key>:range:方法,所以你想重新定義KVC的一些功能,你可以添加這些方法,需要注意的是你的方法名要符合KVC的標準命名方法,包括方法簽名, - 如果上面的方法沒有找到,那么會同時查找
countOf<Key>,enumeratorOf<Key>,memberOf<Key>格式的方法,如果這三個方法都找到,那么就回傳一個可以回應NSSet所的方法的代理集合,和上面一樣,給這個代理集合發NSSet的訊息,就會以countOf<Key>,enumeratorOf<Key>,memberOf<Key>組合的形式呼叫, - 如果還沒有找到,再檢查類方法
+ (BOOL)accessInstanceVariablesDirectly,如果回傳YES(默認行為),那么和先前的設值一樣,會按_<Key>,_is<Key>,<Key>,is<Key>的順序搜索成員變數名,這里不推薦這么做,因為這樣直接訪問實體變數破壞了封裝性,使代碼更脆弱,如果重寫了類方法+ (BOOL)accessInstanceVariablesDirectly回傳NO的話,那么會直接呼叫valueForUndefinedKey: - 還沒有找到的話,呼叫
valueForUndefinedKey:
- 首先按
-
以
[person valueForKey:@"name"];為例getter方法的呼叫順序是:getNamenameisName_name
- 如果以上方法沒有找到,accessInstanceVariablesDirectly回傳YES,則直接回傳成員變數,獲取順序依然是:
_name_isNamenameisName
可通過案例進行驗證,這里不再展示,
-
KVC取值流程圖

可以通過下面的代碼對以上結論進行驗證!
@interface LGPerson : NSObject
{
@public
NSString *_isName;
NSString *name;
NSString *isName;
NSString *_name;
}
@end
@implementation LGPerson
+(BOOL)accessInstanceVariablesDirectly{
return NO;
}
-(id)valueForUndefinedKey:(NSString *)key{
NSLog(@"出現例外,該key不存在%@",key);
return nil;
}
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
NSLog(@"出現例外,該key不存在%@",key);
}
// 設定方法全部注釋掉
// -(void)setName:(NSString*)name{
// toSetName = name;
// }
// - (void)_setName:(NSString *)name{
// NSLog(@"%s - %@",__func__,name);
// }
// - (void)setIsName:(NSString *)name{
// NSLog(@"%s - %@",__func__,name);
// }
// 取值方法
//- (NSString *)getName{
// return NSStringFromSelector(_cmd);
//}
//- (NSString *)name{
// return NSStringFromSelector(_cmd);
//}
//- (NSString *)isName{
// return NSStringFromSelector(_cmd);
//}
//- (NSString *)_name{
// return NSStringFromSelector(_cmd);
//}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
LGPerson* person = [LGPerson new];
[person setValue:@"NewName" forKey:@"name"];
NSString* name = [person valueForKey:@"name"];
NSLog(@"value for key : %@",name);
NSLog(@"取值_name:%@",person->_name);
NSLog(@"取值_isName:%@",person->_isName);
NSLog(@"取值name:%@",person->name);
NSLog(@"取值isName:%@",person->isName);
}
return 0;
}
4.在KVC中使用keyPath
除了對當前物件的屬性進行賦值外,還可以對其更深層的物件進行賦值,例如,對當前物件的location屬性的country屬性進行賦值,KVC進行多級訪問時,直接類似于屬性呼叫一樣用點語法進行訪問即可,
[person setValue:@"" forKeyPath:@"location.country"];
通過keyPath對陣列進行取值時,并且陣列中存盤的物件型別都相同,可以通過valueForKeyPath:方法指定取出陣列中所有物件的某個欄位,例如下面例子中,通過valueForKeyPath:將陣列中所有物件的name屬性值取出,并放入一個陣列中回傳,
NSArray *names = [array valueForKeyPath:@"name"];

5.例外處理
當根據KVC搜索規則,沒有搜索到對應的key或者keyPath,則會呼叫對應的例外方法,例外方法的默認實作,在例外發生時會拋出一個例外,并且應用程式Crash,見下圖:

我們可以重寫下面兩個方法:
-(id)valueForUndefinedKey:(NSString *)key{
NSLog(@"出現例外,該key不存在%@",key);
return nil;
}
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
NSLog(@"出現例外,該key不存在%@",key);
}
重寫這兩個方法之后,運行程式不再崩潰,見下圖:

但是我們可以根據業務需要,合理的處理KVC導致的例外,比如下面的處理方式:
- (void)setNilValueForKey:(NSString *)key {
if ([key isEqualToString:@"name"]) {
[self setValue:@"" forKey:@”age”];
} else {
[super setNilValueForKey:key];
}
}
6.自定義KVC
根據蘋果官方檔案提供的設值、取值規則,我們可以自己進行KVC的自定義實作,見下面實作代碼:
// KVC 自定義
@implementation NSObject (LGKVC)
// 設定
- (void)lg_setValue:(nullable id)value forKey:(NSString *)key{
// 1: 判斷什么 key
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 lg_performSelectorWithMethodName:setKey value:value]) {
NSLog(@"*********%@**********",setKey);
return;
}else if ([self lg_performSelectorWithMethodName:_setKey value:value]) {
NSLog(@"*********%@**********",_setKey);
return;
}else if ([self lg_performSelectorWithMethodName:setIsKey value:value]) {
NSLog(@"*********%@**********",setIsKey);
return;
}
// 3: 判斷是否回應 accessInstanceVariablesDirectly 回傳YES NO 奔潰
// 3:判斷是否能夠直接賦值實體變數——NO
if (![self.class accessInstanceVariablesDirectly] ) {
@throw [NSException exceptionWithName:@"LGUnknownKeyException" 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];
}
// 取值
- (nullable id)lg_valueForKey:(NSString *)key{
// 1:刷選key 判斷非空
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:判斷是否能夠直接賦值實體變數-YES、NO
if (![self.class accessInstanceVariablesDirectly] ) {
@throw [NSException exceptionWithName:@"LGUnknownKeyException" reason:[NSString stringWithFormat:@"****[%@ valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.****",self] userInfo:nil];
}
// 4.找相關實體變數進行賦值
// 4.1 定義一個收集實體變數的可變陣列
NSMutableArray *mArray = [self getIvarListName];
// _<key> _is<Key> <key> is<Key>
// _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 @"";
}
#pragma mark **- 相關方法**
- (BOOL)lg_performSelectorWithMethodName:(NSString *)methodName value:(id)value{
if ([self respondsToSelector:NSSelectorFromString(methodName)]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[self performSelector:NSSelectorFromString(methodName) withObject:value];
#pragma clang diagnostic pop
return YES;
}
return NO;
}
- (id)performSelectorWithMethodName:(NSString *)methodName{
if ([self respondsToSelector:NSSelectorFromString(methodName)]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
return [self performSelector:NSSelectorFromString(methodName) ];
#pragma clang diagnostic pop
}
return nil;
}
- (NSMutableArray *)getIvarListName{
NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:1];
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([self class], &count);
for (int i = 0; i<count; i++) {
Ivar ivar = ivars[i];
const char *ivarNameChar = ivar_getName(ivar);
NSString *ivarName = [NSString stringWithUTF8String:ivarNameChar];
NSLog(@"ivarName == %@",ivarName);
[mArray addObject:ivarName];
}
free(ivars);
return mArray;
}
@end
喜歡的小伙伴記得點贊喔~
收藏等于白嫖,點贊才是真情?( ′・?・` )?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/297613.html
標籤:其他
