用@synthesize生成的setter是否应该是KVC编译器?我发现生成的getter和setter是KVC兼容的,它不应该调用其中的一个方法吗?
@interface testing : NSObject
@property (nonatomic, retain) NSString *phone;
@end实施:
@implementation testing
@synthesize phone;
- (id)init {
self = [super init];
return self;
}
// none of these is called with dot syntax, or setter setPhone
- (void)setValue:(id)value forKey:(NSString *)key
{
NSLog(@"%@",key);
[super setValue:value forKey:key];
}
-(void)setValue:(id)value forKeyPath:(NSString *)keyPath
{
NSLog(@"%@",keyPath);
[super setValue:value forKeyPath:keyPath];
}
@end并使用以下命令进行测试:
testing *t = [[testing alloc] init];
[t setPhone:@"55555555"];发布于 2011-12-05 06:31:45
我想你搞错了..KVC兼容并不意味着访问器将调用-setValue:forKey:兼容KVC意味着调用-setValue:forKey:将调用访问器。
稍微扩展一下:与KVC兼容只意味着“遵循命名约定”。为什么这很重要?我可以将我的存取器方法命名为任何我喜欢的名称。对于属性'Foo':
- (void)weakSetFoo:(id)f;
- (id)autoreleasedFoo;这很好。但是像绑定这样的机制会尝试通过调用
[ob setValue:newVal forKey:@"foo"];-setValue:forKey:将尝试做正确的事情并使用访问器方法(如果我们编写了一个setter方法,那是因为我们希望使用它,对吧?)但是,除非我们将设置方法命名为标准-setFoo:,否则它是不可能被找到的。
所以-weakSetFoo:是一个设置器方法,但是Foo属性不符合KVC。如果我将设置器名称更改为-setFoo:,那么属性Foo现在是KVC兼容的。
默认情况下,合成访问器方法将被正确命名。
发布于 2011-12-05 06:20:39
您不需要为KVO实现setValueForKey:。它在框架中为您实现。通过使你的属性符合KVO (你已经使用@property和@synthesize做到了这一点),一切都变得“神奇”了。
-更新
此外,您的测试代码不会测试KVO。要对其进行测试,请执行以下操作:
testing *t = [[testing alloc] init];
[t setValue:@"55555555" forKey:@"phone"];发布于 2011-12-05 06:25:16
实际上,情况正好相反。这些是setValue:forKey和getValueforKey,它们查找符合KVC的属性,而不是通过它们合成的属性。
当你编写@synthesize property时,编译器实际上只填充了- (type) property和- (void) setProperty: (type)value类的方法,它们读取/设置相应的实例变量。
https://stackoverflow.com/questions/8379014
复制相似问题