• 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的内容

  • 相关阅读:
    Spring MVC 3 深入总结
    精益之识别和消除研发过程中浪费的思路和模式
    怎样区分直连串口线和交叉串口线?
    UVA 10557 XYZZY
    概率论 —— 分析计算机系统和网络的可靠性和通用性
    概率论 —— 分析计算机系统和网络的可靠性和通用性
    Sift中尺度空间、高斯金字塔、差分金字塔(DOG金字塔)、图像金字塔
    鲁迅先生的话
    鲁迅先生的话
    辛词
  • 原文地址:https://www.cnblogs.com/Kenwuqingjian/p/5314454.html
Copyright © 2020-2023  润新知