Objective C - Synthesize property [duplicate]

Possible Duplicate:
Prefixing property names with an underscore in Objective C

When synthesizing properties I found out that someone is doing:

@synthesize myVar = _myVar;

what is "_myVar" and which is the difference with simply doing :

@synthesize myVar;        

Lastly when I should prefer the first solution to the last one?

Thanks Luca


Solution 1:

What _myVar really is in your example, is the name of the ivar that is backing your property. By default, when you synthesize a property, an ivar of the same name is created for you. So, you can use your property to set your ivar through setter/getter or the _myVar to directly access your variable (bypassing KVC/KVO of course).

EDIT: From Apple's Coding Guidelines for Cocoa

...In many cases, when you use a declared property you also synthesize a corresponding instance variable.

Make sure the name of the instance variable concisely describes the attribute stored. Usually, you should not access instance variables directly, instead you should use accessor methods (you do access instance variables directly in init and dealloc methods). To help to signal this, prefix instance variable names with an underscore (_)...