zoukankan      html  css  js  c++  java
  • 关于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。


    }

  • 相关阅读:
    Oracle创建用户并赋予权限
    Oracle查询表空间使用情况
    Oracle更改数据库文件大小、实时增加文件容量
    Oracle查询数据中占用空间最大的表
    Oracle存储包存储及案例
    Oracle包Package调用Package
    Oracle存储过程Procedure语法及案例
    Oracle存储过程function语法及案例
    Oracle常用语法
    Oracle游标循环更新数据案例
  • 原文地址:https://www.cnblogs.com/ly1973/p/3582636.html
Copyright © 2011-2022 走看看