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的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设置值
- (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;
}