2

I just noticed that, for some reason, I don't seem to have automatically created underscore iVars in my iOS 7 project, and I wonder why that is. My setup:

MyClass.h

@property (readonly) NSNumber *aNumber;

MyClass.m

@interface MyClass ()
@property (readwrite, strong) NSNumber *aNumber;
@end

@implementation MyClass

(...)

- (NSNumber *)aNumber {
    return _aNumber;
}

- (void)setANumber:(NSNumber *)aNumber {
    _aNumber = aNumber;
}

@end

This results in Use of undeclared identifier: '_aNumber'.

Why is that so? I thought that underscore iVars are always automatically synthesized? Is it because of the class extension I use? If I put in @synthesize aNumber = _aNumber; it (obviously) works.

BlackWolf
  • 5,239
  • 5
  • 33
  • 60
  • the reason is to avoid generate redundant ivar when you don't need it. – Bryan Chen Jun 09 '14 at 09:27
  • the reason is why not, because you have created a custom getter method, and the auto-synthesize does not create anything for you in that case, you have to do it manually in that case. – holex Jun 09 '14 at 11:00

1 Answers1

3

There is one exception to the automatic synthesize rule.

If you override both the getter and the setter of a property then you will have to manually synthesize the property.

This has been the case ever since auto synthesis came in.

Just add the @synthesize line and it will be fine.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306