KVC

2021-02-27  本文已影响0人  Berning

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赋值

//抛出

exception 'NSUnknownKeyException', 
reason: '[<NSPerson 0x1005acc70> setValue:forUndefinedKey:]:this class is
 not key value coding-compliant for the key age.'
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的返回值

//抛出

exception 'NSUnknownKeyException', 
reason: '[<NSPerson 0x1005acc70> valueForUndefinedKey:]:this class is
 not key value coding-compliant for the key age.'
exception 'NSUnknownKeyException', 
reason: '[<NSPerson 0x1005acc70> setValue:forUndefinedKey:]:this class is
 not key value coding-compliant for the key age.'

KVC触发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];
}
上一篇 下一篇

猜你喜欢

热点阅读