Why use underscore instance value on xcode

2013年3月28日

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.

Have your say