KVC本质

作者: 程序猿_K | 来源:发表于2019-05-19 17:36 被阅读0次

    KVC

    KVC的全称是Key-Value Coding,俗称“键值编码”,可以通过一个key来访问某个属性.

    //API
    - (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
    - (void)setValue:(id)value forKey:(NSString *)key;
    - (id)valueForKeyPath:(NSString *)keyPath;
    - (id)valueForKey:(NSString *)key; 
    

    KVC使用

    //People类
    @interface People : NSObject
    @property(nonatomic, assign)int age;
    @end
    //main
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            // insert code here..
            People *p = [[People alloc] init];
            [p setValue:@10 forKey:@"age"];
            //[p setValue:@10 forKeyPath:@"age"];
            NSLog(@"%d",p.age);
            return 0;
        }
    }
    

    可以看到打印都可以打印出10


    KVC使用

    KVC赋值过程

    KVC赋值

    KVC赋值会触发KVO
    KVO原理类似以下操作:
    1.KVO赋值操作(不管是不是调用set或者直接赋值)
    2.willChangeValueForKey:
    3.didChangeValueForKey:(内部调用通知KVO方法)

    KVC取值过程

    KVC取值

    相关文章

      网友评论

          本文标题:KVC本质

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