KVC基本使用
NSCat *cat = [NSCat new];
NSPerson *person = [NSPerson new];
person.cat =cat;
[person setValue:@10 forKey:@"age"];
[person valueForKey:@"age"];
[person setValue:@"mimi" forKeyPath:@"cat.name"];
[person valueForKey:@"cat.name"];
KVC赋值
- 按照setKey: -> _setKey ->的顺序查找方法,
如果上述方法不存在,判断+accessInstanceVariablesDirectly
的返回值 - if(NSPerson. accessInstanceVariablesDirectly == NO)
//抛出
exception 'NSUnknownKeyException',
reason: '[<NSPerson 0x1005acc70> setValue:forUndefinedKey:]:this class is
not key value coding-compliant for the key age.'
- if (NSPerson. accessInstanceVariablesDirectly == YES)
按照_key-> _isKey ->key -> isKey 的顺序查找成员变量赋值
如果上述成员变量都不存在,抛出
exception 'NSUnknownKeyException',
reason: '[<NSPerson 0x1005acc70> setValue:forUndefinedKey:]:this class is
not key value coding-compliant for the key age.'
KVC取值
按照- getKey -> key ->isKey->_key的顺序查找方法,
如果上述方法不存在,判断+accessInstanceVariablesDirectly
的返回值
- if(NSPerson. accessInstanceVariablesDirectly == NO)
//抛出
exception 'NSUnknownKeyException',
reason: '[<NSPerson 0x1005acc70> valueForUndefinedKey:]:this class is
not key value coding-compliant for the key age.'
- if(NSPerson. accessInstanceVariablesDirectly == YES)
按照_key-> _isKey ->key -> isKey 的顺序查找成员变量赋值
如果上述成员变量都不存在,抛出
exception 'NSUnknownKeyException',
reason: '[<NSPerson 0x1005acc70> setValue:forUndefinedKey:]:this class is
not key value coding-compliant for the key age.'
KVC触发KVO
- 存在
setKey:
方法,会触发KVO - 不存在
setKey:
方法,也会触发KVO(相当于手动触发KVO
)
//伪代码
- (void)setValue:(id)value forKey:(NSString *)key
{
[self willChangeValueForKey:key];
Method method = class_getInstanceMethod(self.class,@selector(setKey:));
IMP imp = method_getImplementation(method);
Method _method = class_getInstanceMethod(self.class,@selector(setKey:));
IMP _imp = method_getImplementation(method);
if (imp != NULL) {
// [self setKey:key];
}
else if (_imp != NULL)
{
// [self _setKey:key];
}
else if(self.class.accessInstanceVariablesDirectly == YES)
{
// if(_key)
// {}
// else if(_iskey)
// {}
// else if(key)
// {}
// else
// {}
}
else
{
@throw @"NSUnknownKeyException,reason:setValue:forUndefinedKey";
}
[self willChangeValueForKey:key];
}
网友评论