When should I explicitly add @synthesize to my code?
As a rule, if it is necessary: you will probably never encounter a situation when it is necessary.
In one case, you may find it useful.
Suppose you write both a custom getter and a setter, but you want the instance variable to return it. (For an atom’s property, this is as simple as the desire for a custom setter: the compiler will write a getter if you specify an installer for a monatomic property, but not an atomic property.)
Consider this:
@interface MyObject:NSObject @property (copy) NSString *title; @end @implementation MyObject - (NSString *)title { return _title; } - (void)setTitle:(NSString *)title { _title = [title copy]; } @end
This will not work because _title does not exist. You specified both getter and setter, so Xcode (correctly) does not create a database instance variable for it.

You have two options for its existence. You can either change @implementation to this:
@implementation MyObject { NSString *_title; } - (NSString *)title { return _title; } - (void)setTitle:(NSString *)title { _title = [title copy]; } @end
Or change it to this:
@implementation MyObject @synthesize title = _title; - (NSString *)title { return _title; } - (void)setTitle:(NSString *)title { _title = [title copy]; } @end
In other words, although synthesis is never needed * for practical purposes, it can be used to define property instance variables when you provide getter / setter. You can decide which form you want to use.
In the past, I preferred to specify an instance variable in @implementation {} , but now I think that the @synthesize route is the best choice, as it removes the redundant type and explicitly binds the substitution variable to the property:
- Change the type of the property and change the type of the instance variable.
- Change your storage classifier (for example, make it weak rather than strong or strong rather than weak) and the storage definition will change.
- Delete or rename the property, and
@synthesize will generate a compiler error. You will not end up with instance instances of variables.
* - I know one case when it was necessary, relating to the division of functions into categories in several files. And I won’t be surprised if Apple fixes it or even already has it.
Steven Fisher Nov 05 '13 at 17:42 2013-11-05 17:42
source share