When I first learned about iOS programming (I believe this was from the pre-ARC Stanford lectures), we always synthesized properties like this:
However, it appears that this has been the default behaviour for a while. So, omitting this statement is the exact same as leaving it in.
My question is this: given this default behaviour, what are some practical examples where we'd actually want to use a @synthesize statement?
Best How To :
With iOS 6, the LLVM compiler came with something called "property autosynthesis". Basically, that means that the compiler will add a
@synthesize for every
@property it sees in the following form:
@synthesize propertyName = _propertyName;
that is, it will create an ivar prefixed with underscore and it will generate the getter & setter using this ivar.
There is only one reason to use
@synthesize explicitly and the reason is to rename the ivar or, for example, use the same ivar for two different properties.
Also note that in some cases you need to use
@dynamic to prevent the synthesis. Typically when you know the methods (getter or setter) are already defined somewhere but the compiler doesn't know about them.
There are no memory implications with autosynthesis so it is not connected to ARC at all.
What if I manually implement getter and a setter?
If the property is readwrite and you implement both setter and a getter or if the property is readonly and you implement the getter, then nothing will be synthesized. The synthesis refers to the automatic definition of the two methods. Why should the compiler synthesize something that is already there? If the manual implementation needs an ivar, just declare the ivar, you don't need to add
@synthesize just to add an ivar (although you can).
I forgot one reason when using
@synthesize is needed and that is when implementing a property declared in a protocol. Such a property won't be autosynthesized. A typical example is