When do you make an underscore in front of an instance variable? [duplicate]
Possible Duplicate:
How does an underscore in front of a variable in a cocoa objective-c class work?
I've seen this at Apple, inside UIPickerView.h:
id<UIPickerViewDataSource> _dataSource;
why's that underscore there? Does it have a special meaning? A Convention I must know about?
A lot of people use this for private variables, to differentiate between private variables and public variables within an object.
It is a completely optional way of working.
What you're seeing is the use of underlines to distinguish between instance variables and properties. So a class declaration might be:
@interface Foo {
NSString* _label;
....
}
@property (nonatomic, retain) NSString* label; // notice: no underline
Then in the implementation file you would have:
@synthesize label=_label; // the property is matched with the ivar
Now when inside the implementation, if you want to access the instance variable directly you could just use _label
but to go through the property accessor methods (which take care of retain/releases and a bunch of other book-keeping tasks) you would use self.label
. From the outside, you would always want to go through the {object}.label
property.
The other way is to do without the underline and just use:
NSString* label;
@property (nonatomic, retain) NSString* label;
...
@synthesize label;
It works the same but then it might confuse someone reading the code and trying to keep track of label
vs self.label
. I personally find the Apple convention (with underlines) a bit easier to read but it's a matter of preference.
As people said already _someVar was used to say that a variable was private. It was a simple matter of convention and doesn't really matter.
One other use, taking a trip in the wayback machine in C a _function() represented a function that wasn't platform portable and __function() represented a function that wasn't compiler portable. So, in the standard C library, you will sometimes see a variable with a _ or __ infront of the name, this is what those functions represent.
It's sometimes used to denote private variables. More generally it just means "this variable is different somehow".