Objective c 使用自定义getter、setter和ivar进行键值编码
我想知道当Objective-C中定义了自定义的getter、setter和ivar时,访问属性值的键值编码是如何工作的。根据这个例子,运行时将首先搜索getter方法,然后返回到使用反射字符串查找ivar 根据搜索模式,当既找不到getter也找不到ivar时,应该抛出异常 但是,当我运行以下代码时:Objective c 使用自定义getter、setter和ivar进行键值编码,objective-c,kvc,Objective C,Kvc,我想知道当Objective-C中定义了自定义的getter、setter和ivar时,访问属性值的键值编码是如何工作的。根据这个例子,运行时将首先搜索getter方法,然后返回到使用反射字符串查找ivar 根据搜索模式,当既找不到getter也找不到ivar时,应该抛出异常 但是,当我运行以下代码时: #import <Foundation/Foundation.h> @interface Class1 : NSObject { NSInteger prop; } @p
#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]);
}
似乎我得到了两个不同的值:直接从属性读取时检索通过直接访问属性设置的值(9
)。通过键值编码(20
)检索使用键值编码设置的值
有人知道这在内部是如何工作的吗?这种行为是预期的吗?我遗漏了什么吗?将以下方法添加到您的
Class1
:
- (void) showVars
{
NSLog(@"->prop %ld | ->customIVar %ld", prop1, customIvar);
}
在你改变你的财产后再打电话,你会看到发生了什么
阅读你链接到的参考资料,它说明了如何搜索getter和setter
你已经找到了答案
它有很好的文档记录吗?可能不是,Objective-C&Cocoa没有正式的语义描述:-(
HTH谢谢你的回答。我看到ivar的值与属性的值不同。我已经彻底阅读了参考资料,不明白你的意思。你能再详细一点吗?KVC搜索算法的描述明确指定了它搜索的方法和变量名称;这些不包括任何自定义名称getter、setor或var名称。。。
- (void) showVars
{
NSLog(@"->prop %ld | ->customIVar %ld", prop1, customIvar);
}