问题描述
我不能在目标c中这样做吗?
Can I not do this in objective c?
@interface Foo : NSObject {
int apple;
int banana;
}
@property int fruitCount;
@end
@implementation Foo
@synthesize fruitCount; //without this compiler errors when trying to access fruitCount
-(int)getFruitCount {
return apple + banana;
}
-(void)setFruitCount:(int)value {
apple = value / 2;
banana = value / 2;
}
@end
我正在使用类这个:
Foo *foo = [[Foo alloc] init];
foo.fruitCount = 7;
但是我的getter和setter没有被调用。如果我改为写:
However my getter and setter's are not getting called. If I instead write:
@property (getter=getFruitCount, setter=setFruitCount:) int fruitCount;
我的getter被调用但是setter仍然没有被调用。我缺少什么?
My getter gets called however the setter still doesn't get called. What am I missing?
推荐答案
你的语法有点偏......
定义你自己的属性实现在您的示例中使用以下内容:
Your syntax is a bit off...to define your own implementation for property accessors in your example, use the following:
@implementation Foo
@dynamic fruitCount;
-(int)fruitCount {
return apple + banana;
}
-(void)setFruitCount:(int)value {
apple = value / 2;
banana = value / 2;
}
@end
使用 @synthesize
告诉编译器创建默认访问器,在这种情况下你显然不需要。 @dynamic
向编译器指示您将编写它们。以前在Apple的文档中有一个很好的例子,但它在4.0 SDK更新中以某种方式被破坏了...希望有所帮助!
Using @synthesize
tells the compiler to make default accessors, which you obviously don't want in this case. @dynamic
indicates to the compiler that you will write them. There used to be a good example in Apple's documentation, but it somehow got destroyed in their 4.0 SDK update... Hope that helps!
这篇关于getter和setter不工作目标c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!