kvc

作者: 温柔的熊 | 来源:发表于2021-10-14 14:54 被阅读0次

    kvc是英文key value code的缩写,直译就是键值编码。通过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来设值
    

    在使用上面的方法时,如果key或者keyPath不存在会抛出异常。

    keyPath

    keyPath是一个访问路径,当一个类的属性是一个比较复杂的数据结构时,这种访问方式更快捷。

    @interface Room : NSObject
    @property (nonatomic, strong) Television *television;
    @property (nonatomic, strong) Person *person;
    @end
    
    @interface Person : NSObject
    @property (nonatomic, assign) int age;
    @end
    
    Room *room = [Room alloc]init];
    int age = [[room valueForKeyPath:@"person.age"] intValue];
    

    相关文章

      网友评论

          本文标题:kvc

          本文链接:https://www.haomeiwen.com/subject/wsfuoltx.html