getter和setter不工作目标c

ody*_*yth 4 objective-c ios4 ios

我不能在目标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
Run Code Online (Sandbox Code Playgroud)

我正在使用这样的类:

Foo *foo = [[Foo alloc] init];
foo.fruitCount = 7;
Run Code Online (Sandbox Code Playgroud)

然而,我的getter和setter没有被调用.如果我改为写:

 @property (getter=getFruitCount, setter=setFruitCount:) int fruitCount;
Run Code Online (Sandbox Code Playgroud)

我的getter被调用但是setter仍然没有被调用.我错过了什么?

Mec*_*han 10

您的语法稍微有点......在您的示例中为属性访问器定义自己的实现,请使用以下命令:

@implementation Foo
@dynamic fruitCount;

-(int)fruitCount {
   return apple + banana;
}
-(void)setFruitCount:(int)value {
      apple = value / 2;
      banana = value / 2;
}

@end
Run Code Online (Sandbox Code Playgroud)

使用@synthesize告诉编译器创建默认访问器,在这种情况下您显然不需要.@dynamic向编译器指示您将编写它们.以前在Apple的文档中有一个很好的例子,但它在4.0 SDK更新中以某种方式被破坏了...希望有所帮助!