Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 838
Kevin Renskers Avatar asked Oct 16 '12 15:10

Kevin Renskers


People also ask

What does @synthesize do Obj C?

@synthesize tells the compiler to take care of the accessor methods creation i.e it will generate the methods based on property description. It will also generate an instance variable to be used which you can specify as above, as a convention it starts with _(underscore)+propertyName.

What is @synthesize in IOS?

It will generate an instance variable for the property's storage, using the naming convention with the leading underscore, or use an instance variable of that name if you explicitly declared one. It will also generate the accessor methods with the proper semantics to match the @property declaration.

Why @property and @synthesize do not exist for a property in Swift?

Swift provides no differentiation between properties and instance variables (i.e, the underlying store for a property). To define a property, you simply declare a variable in the context of a class.

What does @dynamic do in Objective C?

@dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass or will be provided at runtime).


1 Answers

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.

like image 144
Eiko Avatar answered Oct 11 '22 18:10

Eiko