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

  • 相关阅读:
    ASP.NET MVC中几个运用技巧
    Excel VBA 编程语法下
    C# 给窗体添加皮肤 SkinEngine的应用
    Windows Intune beta版发布
    简单对象使用方法
    Excel ActiveX 简介—常用控件ComboBox
    Thinking of Consultant:Trustworthy
    unity学习日志1
    Idea设置编辑区字体快捷键
    mysql Communications link failure的解决办法
  • 原文地址:https://www.cnblogs.com/Kenwuqingjian/p/5314454.html
Copyright © 2020-2023  润新知