0

I am building a database migration tool that is a Mac app and I am running into a strange issue making custom getter/setters for a property.

For a property named parentStore, I have this getter:

- (CCStore *)parentStore {
    if (!_parentStore) {
        _parentStore = [[CCStore alloc] initWithStoreID:self.storeID];
    }

    return _parentStore;
}

Pretty straight forward, no issues there.

Now when I try and make a custom setter, Xcode blows up on me.

- (void)setParentStore:(CCStore *)parentStore {

}

I no sooner finish typing the signature on this setter than Xcode claims that the use of _parentStore up above in the getter is an undeclared identifier. I am running on little sleep so I could just be doing something dumb, but I can not figure it out what is going on!!!

Screen shot shown below:

enter image description here

Lizza
  • 2,769
  • 5
  • 39
  • 72

1 Answers1

2

If you override both the getter and the setter, you're basically saying that you don't want llvm to provide a synthesized backing ivar. It would be a waste, since it doesn't know if you're going to use it or not.

Just declare the ivar yourself in your class:

@implementation MyClass

@synthesize parentStore = _parentStore;

- (CCStore *)parentStore
{
  if (!_parentStore) {
    _parentStore = [[CCStore alloc] initWithStoreID:self.storeID];
  }
  return _parentStore;
}

- (void)setParentStore:(CCStore *)parentStore
{
  // do nothing
}

Since you ignore the setter, it's best practice to make this a read-only property and then not define the setter at all.

Jason Coco
  • 77,985
  • 20
  • 184
  • 180
  • 1
    `@dynamic` means that the property accessors will be provided at *runtime* and it not necessary here. It is sufficient to declare the ivar *or* an explicit `@synthesize parentStore = _parentStore`. – Martin R Jun 17 '14 at 04:17
  • @MartinR is correct, you don't need the `@dynmaic`. I am going to update the answer to reflect the assigned synthesizer. We often use abstract class factory patterns and define the actual properties in the concrete subclasses. – Jason Coco Jun 17 '14 at 04:49