我不能在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没有被调用。如果我改为这样写:
@property (getter=getFruitCount, setter=setFruitCount:) int fruitCount;我的getter被调用了,但是setter仍然没有被调用。我遗漏了什么?
发布于 2011-07-27 10:47:21
你的语法有点不对劲...要在示例中定义自己的属性访问器实现,请使用以下内容:
@implementation Foo
@dynamic fruitCount;
// ⚠ NOTE that below has NOT "getFruitCount" name.
- (int) fruitCount {
return apple + banana;
}
- (void) setFruitCount :(int)value {
apple = value / 2;
banana = value / 2;
}
@end使用@synthesize告诉编译器建立默认的访问器,在这种情况下,您显然不希望这样做。@dynamic向编译器表明您将编写它们。苹果的文档中曾经有一个很好的例子,但不知何故在他们的4.0 SDK更新中被破坏了……希望这能有所帮助!
https://stackoverflow.com/questions/6838852
复制相似问题