• 关于KVC、KVO


    KVC/KVO

    --------------------KVC--键值编码-------------------
    作用:
    通过字符串来描述对象的属性间接修改对象的属性

    Student *stu=[[Student alloc]init];//实例化Student 对象
    Student 成员变量:name ,age, book
    Book 成员变量 price

    1 修改price属性

    [stu setValue @“10.3”forKey:@“age”]

    1.0获取属性值
    [stu valueForkey:@"age"];


    2 批量修改属性

    [stu setValuesWithDictionary:@ {@"age":@"22",@"name":@"傻强"}];
    2.0获取批量值(返回值字典)
    NSArray *array= [stu dictionaryWithValues:@[@"age",@"name"]];

    3 修改属性对象的属性
    stu.book=[[BOOK alloc]init];

    [stu.book setValue:@10.7 ForKey:@"price"];
    [stu setValue:@"10.7" ForKeyPath:@"book.price"];

    4 直接获取数组中所有对象的name属性值(name为对象的属性)

    Student *stu1=[[Student alloc]init];
    Student *stu2=[[Student alloc]init];
    Student *stu3=[[Student alloc]init];
    NSArray *array=@[stu1,stu2,stu3];

    NSArray *nameArray=[array valueForKeyPath:@"name"];

    5 直接获取数组中所有对象的price属性值的和(price为对象的属性对象book的属性)

    stu1.book=[[BOOK alloc]init];
    stu1.book.price=15;

    stu2.book=[[BOOK alloc]init];
    stu2.book.price=20;

    stu3.book=[[BOOK alloc]init];
    stu3.book.price=25;
    NSArray *sumPrice=@[stu1,stu2,stu3];

    id sum=[sumPrice valueForKeyPath:book.@sum.price];

    --------------------KVO--键值监听-------------------

    作用:
    监听对象的属性的变化

    下面以用Student对象来监听BOOK对象的price属性值的变化为例
    ------------------BOOK.m------------------------
    BOOK *book=[[BOOK alloc]init];
    book.price=10;//price原来的值

    Student *stu=[[Student alloc]init];
    //添加监听器
    [book addObserver:stu forKeyPath:@"price" options:NSKeyValueObserverOptionNew |NSKeyValueObserverOptionOld context:nil];
    //book:添加监听器者,stu:被添加监听器者,price:监听对象的什么属性,options:监听类型 context:上下文,这里暂时不需要,可填写为空;

    book.price=50;//price变化后的值

    //移出监听器
    [book removeObserver:stu forKeyPath :@"price"]

    ------------------Student.m------------------

    //当所监听的属性发生改变的时候,会调用这个方法

    - (void)observerValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {

    //keyPath:被监听的属性,这里为name。
    //object:哪个对象的属性,这里为book。
    //change :属性值变化为什么(字典),这里为old=10,new=50.
    //context:上下文为nil。


    }

  • 相关阅读:
    1、PHP入门二维数组与循环
    Nginx 配置反向代理后,页面中取绝对URL地址的问题显示代理端口
    苹果手机上点击WEUI日期控件不容易点中
    ios 不支持-,-时间。
    Newtonsoft.Json添加项
    Baidu地图Map api直接加https不起作用
    腾讯云cos封装
    linux连接工具隧道模式
    微信调试工具测试时有时候复制URL没有corpid解决
    WEUI控件JS用法
  • 原文地址:https://www.cnblogs.com/ly1973/p/3582636.html
Copyright © 2020-2023  润新知