1

I am confused by something that I need some help with. I thought I did understand basic @property / @synthesize I have a custom ViewController class and I have following declaration in ,h file:

@property (nonatomic) NSMutableArray *milestoneViews;

Rather than using @synthesize, I tried to use my own getter and setter ...

So, I created following function in .m file -

-(NSMutableArray*) milestoneViews{
    if (_milestoneViews == nil) {
        _milestoneViews = [[NSMutableArray alloc]init];
    }
    return _milestoneViews;
}

It compiled fine. But when I started to write setter like this :

-(void) setMilestoneViews:(NSMutableArray*) array
{...}

I got the compilation error on all references to _milestoneViews.

What am I missing?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Don't feel to bad about being confused. Sometimes it seems like Apple changes how they work every six months (though realistically i suppose it's more like every 18 months). – Hot Licks Jul 06 '14 at 03:17

1 Answers1

0

When the compiler sees a read/write property with a hand-written getter, or a hand-written setter, it synthesizes a backing instance variable for you. However, when it detects both a hand-written getter and a hand-written setter, it decides that since you have implemented both methods, it does not need to synthesize anything.

This means that if you wish to write both a getter and a setter manually, you need to add your own instance variable to the class. Typically, you do that in a class extension or the @implementation block, to keep the declaration private to your implementation:

@interface MyClass() {
//                ^^
//                ||
//        Marks the extension

    NSMutableArray *_milestoneViews;

}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • FYI - you don't need a class extension for this. I always add my ivars to the `@implementation` block. Either works. – rmaddy Jul 06 '14 at 03:41