objective-cpropertiessynthesize

Why do I need to write @synthesize when I provide getter and setter?


So the auto synthesize of properties is awesome. However, when you provide both a getter and a setter, you get an error.

@property (strong, nonatomic) NSArray *testArray;

- (NSArray *)testArray {
    return _testArray;
}

- (void)setTestArray:(NSArray *)testArray {
    _testArray = testArray;
}

Error: Use of undeclared identifier '_testArray'.

Adding @synthesize testArray = _testArray; solves the problem. I am just wondering why this is?


Solution

  • When you provide both getter and setter, there is often just no need for an instance variable at all, i.e. when you just forward those messages or store data in other places.

    As soon as one of them is missing, the ivar is needed to synthesize that functionality.

    If I remember correctly, for readonly properties the analogue assumption holds as well.