【问题标题】:KVC Compliant a ClassKVC 兼容类
【发布时间】:2013-01-20 15:33:43
【问题描述】:

在 iOS 文档中读取 KVC Compliant 时。我试图测试一个类。是否符合 KVC 类?

但我有一些问题:

  1. 没有属性“名称”、“年龄”的设置器,并且该类仍在使用 KVC 且没有错误 并且不会触发任何异常

  2. 当没有为属性创建 setter 时,编译器会做什么?可以 创建 setter 和 getter 对?

    人.h

    @interface Person : NSObject
    {
        NSString *name;
        NSInteger age;
    }
    

    人.m

    @implementation Person
    
    - (id)init
    {
        self = [super init];
        if (self) {
            name = @"Duc Nguyen";
            age = 10;
        }
        return self;
    }
    

    ViewController.m

    - (IBAction)showKeyKVC:(id)sender {
        //--test kvc
        name1.text = [person valueForKey:@"name"];
        age1.text = [NSString stringWithFormat:@"%@", [person valueForKey:@"age"]];
    }
    

当我按下按钮时,结果是:年龄:10,姓名:Duc Nguyen。 我不明白在这种情况下该类如何使用 KVC?

【问题讨论】:

    标签: objective-c cocoa kvc


    【解决方案1】:

    答案在Accessor Search Patterns for Simple Attributes KVC 指南中。

    setValue:forKey: 的默认搜索模式:

    当为属性调用setValue:forKey: 的默认实现时,将使用以下搜索模式:

    1. 在接收者的类中搜索名称与模式set<Key>: 匹配的访问器方法。
    2. 如果没有找到访问器,并且接收者的类方法accessInstanceVariablesDirectly返回YES,则在接收者中搜索名称与模式_<key>_is<Key><key>或@987654329匹配的实例变量@,按此顺序。

    默认实现是对accessInstanceVariablesDirectly方法返回YES,所以KVC机制实际上是从nameage实例变量中获取值。

    【讨论】:

    • 出于这个原因,我强烈建议覆盖+accessInstanceVariablesDirectly 以返回NO 用于所有自定义类。 KVC 直接访问实例变量的方式是严重违反封装并隐藏错误。
    猜你喜欢
    • 1970-01-01
    • 2011-07-17
    • 2011-02-14
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 2018-07-20
    相关资源
    最近更新 更多