Search code examples
iosobjective-cios4

getter and setters not working objective 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

I am using the class like this:

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

However my getter and setter's are not getting called. If I instead write:

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

My getter gets called however the setter still doesn't get called. What am I missing?


Solution

  • Your syntax is a bit off... to define your own implementation for property accessors in your example, use the following:

    @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
    

    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!