getter和setter不工作目标c
我不能在目标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没有被调用。 如果我反而写:
@property (getter=getFruitCount, setter=setFruitCount:) int fruitCount;
我的getter被调用但是setter仍然没有被调用。 我错过了什么?
您的语法稍微有点……在您的示例中为属性访问器定义自己的实现,请使用以下命令:
@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更新中以某种方式被破坏…希望有所帮助!