• Objective-C的KVC和KVO


    KVC- Key-Value Coding.

    KVO Key-Value Observing.

     

    KVC是Objective-C提供的一种对象属性的访问机制。对于有面向对象编程习惯的程序员,这是别开生面的方式:不需要在源码通过特殊标志符“." 或 "->"来访问属性;KVC只需要在运行时提供属性名/路径名,就能获得某属性的值。

     

    范例:

    @interface Student : NSObject

    {

    NSString *name;

    }

    @end

     

    @implementation Student

     

    @end

     

    ///////通过Key访问属性name

     

    Student * stu=[ [Student alloc] init];

     

    [stu setValue:@"Ken Wu" forKey:@"name"];

    NSString *newname = [stu valueForKey:@"name"]; //newname的值就是“Ken Wu"。

     

    如果是复杂的对象,如以下Student有课程信息,记录其分数。

    @interface Course : NSObject

    {

    NSString *name;

    float score;

    }

    @end

     

    @implementation Course

    @end

    @interface Student : NSObject

    {

    NSString *name;

    Course *course;

    }

    @end

     

    @implementation Student

    @end

     

    //////通过KeyPath访问课程分数

    Student * stu=[ [Student alloc] init];

     

    [stu setValue:@"Ken Wu" forKey:@"name"];

    NSString *newname = [stu valueForKey:@"name"]; //newname的值就是“Ken Wu"。

     

    [stu setValue:@"Ken Wu" forKey:@"name"];

    Course *course =[ [Course alloc] init];

    [stu setValue:course forKey:@"course"];

    [stu setValue:@"科目1" forKeyPath:@"course.name"];

    [stu setValue: 99.9 forKeyPath:@"course.score"];

     

    float score = [stu valueForKeyPath:@"corse.score"]; //score的值就是 99.9

     

    以上就是KVC的内容

    KVO则在此基础上,对对象属性的变化增加了观察机制。一旦值发生了改变,就会回调已知函数

    observeValueForKeyPath:(NSString *)keyPath
                          ofObject:(id)object
                            change:(NSDictionary *)change
                           context:(void *)context

    范例:

    [stu addObserver:self forKeyPath:@"corse.score" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];

     

    -(void)

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

    If([keyPath isEqualToString:@"corse.score"]){

    float newScore = [change objectForKey:@"new"];

    float oldScore = [change objectForKey:@"old"];

    If(newScore > oldScore){

    NSLog(@"You made a progress!");

    }

    Else {

    NSLog(@"You need move luck!");

    }

    }

    }

     

    以上就是KVO的内容

  • 相关阅读:
    Python_抽象类和接口类
    VS打包项目
    SqlServer 逗号分隔字段查找对应字段值,结果用逗号隔开
    二十一、位置和尺寸
    十三、TableLayout 表格布局
    十一、RelativeLayout 布局
    二十、动画属性动画
    十六、ListView
    十五、ConstraintLayout 限制布局
    十九、动画补间动画
  • 原文地址:https://www.cnblogs.com/Kenwuqingjian/p/5314454.html
Copyright © 2020-2023  润新知