An Objective-C property usually has a backing instance variable (I guess you know the difference between a property and an instance variable).
The property may have a different name than the instance variable.
For instance, you may have an instance variable named x
, with a property named y
.
You can synthesize the y
property to the x
variable using:
@synthesize y = x;
Now about the underscore.
It's a common practice to use an underscore prefix for instance variables, to prevent naming collisions, or compiler warnings (shadowed variable), when having for instance a method argument with the same name as an instance variable.
The underscore prefix also makes clear that you are referring to an instance variable.
By using the underscore prefix for instance variables, you're free to use the name without the underscore in method's arguments, stack variables, etc.
But when using a property, you usually don't want the user to write an underscore.
So you usually have an x
property for an _x
instance variable.
This is why you write:
@synthesize x = _x;
Let's take an example:
@interface Test: NSObject
{
int x;
}
@property( readonly ) int x;
@end
This is quite common... But now imagine this in the implementation:
- ( id )initWithX: ( int )x
{}
We have are a naming collision.
Inside our method, x
will refer to the method's argument. And there is no pretty way to access the x
instance variable.
Depending on your compiler's warning flags, this may also generate a warning (-Wshadow
).
If you use an underscore prefix for your instance variable, everything is just simple:
- ( id )initWithX: ( int )x
{
if( ( self = [ super init ] ) )
{
_x = x;
}
return self;
}
No conflict, no naming collision, improved reading... Just a nice way...