Getter and setters do not work

Can I 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 

I use the class as follows:

 Foo *foo = [[Foo alloc] init]; foo.fruitCount = 7; 

However, my recipient and setter are not called. If I write instead:

  @property (getter=getFruitCount, setter=setFruitCount:) int fruitCount; 

My recipient receives a call, but the setter is still not called. What am I missing?

Thanks,

+4
source share
1 answer

Your syntax is a bit off ... to define your own implementation for property accessories 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 

Using @synthesize , it tells the compiler that it should make default accessors that you obviously don't need in this case. @dynamic tells the compiler to write them. It used to be a good example in the Apple documentation, but it was somehow destroyed in the 4.0 SDK update ... Hope this helps!

+9
source

All Articles