Possible Duplicate:
How does an underscore in front of a variable in a cocoa objective-c class work?
It is not fully clear to me (other than for readability of the code), why you wanna create an internal variable with an underscore prefix when you create the property.
Since everything is handled internally, why bother to do so, since we do not add any code to the getter and setter?
And even if i gotta add some code to the getter or setter, i do not see why i cannot just do the check on myvar instead than having to check _myvar and then assign it to myvar.
Can anyone give me some explanation, other than “do it because that’s what everyone does ?” I would like to understand the whole reason behind this practice (that seems to be pretty common even if there is no custom code for the getter and setter).
Thanks!
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 namedy.You can synthesize the
yproperty to thexvariable using: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
xproperty for an_xinstance variable.This is why you write:
Let’s take an example:
This is quite common… But now imagine this in the implementation:
We have are a naming collision.
Inside our method,
xwill refer to the method’s argument. And there is no pretty way to access thexinstance 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:
No conflict, no naming collision, improved reading… Just a nice way…