美文网首页OC语法iOS Developer程序员
用例子讲KVC的道理 [iOS Objective-C]

用例子讲KVC的道理 [iOS Objective-C]

作者: TEASON | 来源:发表于2015-11-18 12:41 被阅读725次

    KVC非常的灵活,它可以做许多你想不到的事情 .
    教程不如例子能看懂,我整理后出了demo在这里
    代码有两个demo, 第一个demo是讲KVC解析, 本文内容在第二个demo方法里

    NSKeyValueCoding

    这种统一的直接通过字符串存取ObjC中对象的成员属性的接口,可以实现由外部脚本控件程序执行或者获取程序执行信息。
    通过KVC存取二进制库中的私有成员也比较实用。
    也是使用KVO和CoreData的基础。

    先看这个Class

    
    
    @interface Teacher : NSObject
    {
        @private
        NSNumber *age ;  
    }
    @property (nonatomic,copy,readonly)     NSString   *name ;
    @property (nonatomic,strong)            Student    *student ;
    - (instancetype)initWithStudent:(Student *)student ;
    - (void)logAge ;
    @end
    
    看到这个类有私有变量,和只读变量, 如果用一般的settergetter, 在类外部是者访问到私有变量的, 不能重写只读变量,那是不是就拿它没办法了呢?

    然而KVC就是这么神奇


    KVC精华总结

    1.修改只读readonly变量
    readonly只读. 是不能直接赋值的, 但是KVC可以 .
    **e.g. **
    如果想这样~~teacher1.name = @"张三" ~~ 是不行的,因为name是只读变量. 可以通过KVC

        [teacher1 setValue:@"Teacher_teason" forKey:@"name"] ;
    

    2.修改私有private变量
    KVC可以修改一个对象的属性和变量, 即使它是私有的.
    e.g.
    teacher1.age = 24 ;肯定不能用了

        [teacher1 setValue:@24 forKey:@"age"] ; 
    

    如果变量名字为"_age"那么用age和_age`都可以, KVC内部逻辑是先查找age在查找_age

    3.通过运算符层次查找对象的属性

        Student *student1 = [[Student alloc] initWithName:@"Student_Teason" bookList:mutableList] ;
        Teacher *teacher1 = [[Teacher alloc] initWithStudent:student1] ;
    
        NSLog(@"All book name  : %@",[teacher1 valueForKeyPath:@"student.bookList.name"]) ;
        NSLog(@"All book name  : %@",[student1 valueForKeyPath:@"bookList.name"]) ;```
    这两个打印的结果是一样的 .通过keyPath直接访问属性.
    > **All book name  : (**
    **    book10,**
    **    book11,**
    **    book12,**
    **    book13,**
    **    book14,**
    **    book15,**
    **    book16,**
    **    book17,**
    **    book18,**
    **    book19,**
    **    book20**
    **)**
    
    4.获取数组
    
    for (Book *book in [student1 valueForKey:@"bookList"]) { 
    // [student1 valueForKey:@"bookList"]返回一个数组
        NSLog(@"bookName : %@ \t price : %f",book.name,book.price) ;
    }```
    

    5.对属性进行数学运算

        NSLog(@"sum of book price : %@",[student1 valueForKeyPath:@"bookList.@sum.price"]) ;
        NSLog(@"avg of book price : %@",[student1 valueForKeyPath:@"bookList.@avg.price"]) ;```
    
    
    so that's it.
    demo[Github地址](https://github.com/Akateason/Demo_KVC)
    如果觉得豁然开朗,可以去demo点个Star,你的举手之劳,对我的鼓励是巨大的。
    
    > 相关
    详解KVC1http://www.jianshu.com/p/ddff26a58172
    详解KVC2http://www.jianshu.com/p/0a2d5ff328d2
    http://www.bubuko.com/infodetail-919348.html

    相关文章

      网友评论

      • 阿拉斯加的狗:如果变量名字为"_age"那么用age和_age`都可以, KVC内部逻辑是先查找age在查找_age

        楼主顺序弄反了吧 应该是先找带下划线的

      本文标题:用例子讲KVC的道理 [iOS Objective-C]

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