【问题标题】:Key-Value Coding with custom getter, setter and ivar使用自定义 getter、setter 和 ivar 进行键值编码
【发布时间】:2016-12-15 09:02:50
【问题描述】:

我想知道当该属性定义了自定义 getter、setter 和 ivar 时,用于访问属性值的键值编码如何在 Objective-C 中工作。根据Accessor Search Patterns,运行时将首先搜索 getter 方法,然后使用反射字符串查找 ivar。

根据搜索模式,当既没有找到getter也没有找到ivar时,应该抛出异常。

但是,当我运行以下代码时:

#import <Foundation/Foundation.h>

@interface Class1 : NSObject {
    NSInteger prop;
}

@property (getter=customGetter,setter=customSetter:) NSInteger prop;

@end

@implementation Class1
@synthesize prop = customIvar;

@end

int main() {
    Class1 *class1;

    // Create and give the properties some values with KVC...
    class1 = [[Class1 alloc] init];

    class1.prop = 9;
    NSLog(@"Set value to 9 with direct access");

    // Directly access value, should return 9.
    NSLog(@"Direct access: %ld", class1.prop);

    // Set with setValue:forKey: to 20.
    NSLog(@"Set value to 20 with KVC");

    [class1 setValue:[NSNumber numberWithInt:20] forKey:@"prop"];

    // Directly access value.
    NSLog(@"Direct access: %ld", class1.prop);

    // Access value using KVC
    NSNumber *propVal = [class1 valueForKey:@"prop"];

    NSLog(@"ValueForKey access: %d", [propVal intValue]);
}

我得到这个输出:

Set value to 9 with direct access
Direct access: 9
Set value to 20 with KVC
Direct access: 9
ValueForKey access: 20

似乎我得到了两个不同的值:直接从属性读取时检索通过直接访问属性设置的值 (9)。使用键值编码设置的值是使用键值编码 (20) 检索的。

有人知道这在内部是如何工作的吗?这是预期的行为吗?我是否遗漏了什么?

【问题讨论】:

    标签: objective-c kvc


    【解决方案1】:

    将以下方法添加到您的Class1

    - (void) showVars
    {
       NSLog(@"->prop %ld | ->customIVar %ld", prop1, customIvar);
    }
    

    在你改变你的财产后调用它,你会看到发生了什么。

    阅读您链接到的参考资料,它对搜索 getter 和 setter 有什么看法?

    你已经找到答案了。

    是否有据可查?可能不是,Objective-C 和 Cocoa 没有正式的语义描述 :-(

    HTH

    【讨论】:

    • 感谢您的回答。我看到 ivar 的值与属性的值不同。我已经彻底阅读了参考资料,没有明白你的意思。你能详细说明一下吗?
    • KVC 搜索算法的描述明确指定了它搜索的方法和 var 名称;并且那些不包括任何自定义 getter、settor 或 var 名称...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多