【发布时间】: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