2

Possible Duplicate:
property not working with getter AND setter

this is the problem I'm facing: I'm using iOS 6. I declare a property in the header file:

@property (nonatomic) CGFloat scale;

Then in the implementation, I create my own getter/setter like this:

#define DEFAULT_SCALE 0.90    

- (void)setScale:(CGFloat)scale
{
    if(_scale != scale) {
        _scale = scale;
        [self setNeedsDisplay];
    }
}

- (CGFloat) scale
{
    if(!_scale) {
        return DEFAULT_SCALE;
    } else {
        return _scale;
    }
}

the problem is that _scale is not recognized by compiler. I get error "Use of undeclared identifier '_scale'. If I remove the getter or the setter, then it works fine, but I can't keep both. If I do, I have to add @synthesize scale = _scale to avoid the error. Can someone explain why?

Thanks

Community
  • 1
  • 1
damian
  • 4,024
  • 5
  • 35
  • 53
  • 3
    LOL! Take a look at my question from yesterday http://stackoverflow.com/questions/13817562/property-not-working-with-getter-and-setter A good link given to more reading about htis. – Fogmeister Dec 12 '12 at 15:40
  • This has been asked soooooo many times... –  Dec 12 '12 at 19:22

2 Answers2

6

You need to declare the instance variable in the @interface if you're going to use your own setter/getter:

@interface MyClass : NSObject
{
    CGFloat _scale;
}
...
@end

EDIT (after OP question):

Your particular implementation certainly makes a difference (they aren't simple getter/setter methods as they do something as a side-effect). However I think it's always a good idea to declare your variables and absolutely necessary if you want to target 32-bit OSX, as the runtime doesn't support auto-declared instance variables.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • thanks trojanfoe. question: is this a better approach than adding @synthesize in the implementation? or it makes no difference? – damian Dec 12 '12 at 15:44
1

If you provide a full implementation (getter and setter) the compiler assumes you won't need an ivar so if you still want one, you have to create one yourself. Either make an ivar or let @synthesize do it for you. The end result is the same (an ivar is created); the only difference is in the first case you can actually call it whatever you want.

Slightly different but related I often have a

@property (nonatomic,readonly) SomeThing* something;

and provide a method

- (Something*) something { return xxxxxx; }

for cases where you have a method that returns something but having a property is a shortcut.

ahwulf
  • 2,584
  • 15
  • 29