Possible Duplicate:
Prefixing property names with an underscore in Objective C
In Objective-C book i am reading and in some of the code i saw, sometimes, people add underscores to the variable names.
While i realize that this is due to an established convention, I wonder:
Is there any significance whether underscore precedes or completes variable name?
For example take _name, name and name_
As Objective-C programmer, what if anything, does underscore signify to you?
This is largely down to personal style and defensive programming. But here is the main reason why I personally use and have seen people use the prefix.
It is to do with making your intent clearer about whether you are accessing the ivar directly or using the getter/setter.
If I have:
@property (nonatomic, retain) NSArray *people;
and:
@synthesize people = _people;
This will compile and produce the getter/setter declarations like this:
- (void)setPeople:(NSArray *)people;
- (NSArray *)people;
Now to directly access the ivar I need to use:
_people
To use the getter/setter I can use dot notation or the getter/setter like:
[self people];
// or
self.people; // which compiles to [self people];
// and
[self setPeople:newPeople];
// or
self.people = newPeople; // which compiles to [self setPeople:newPeople];
Now in my code if I accidentally just type:
people = newPeople; // will not compile
it will not compile because I am not using the getter/setter and there is no ivar called people
it should be _people
.
A single leading underscore is an Apple internal coding convention, and they do it so that their symbols won't collide with yours. Unfortunately, Apple's been sloppy about publishing code examples that follow this habit, so a lot of people outside of Apple have gotten the idea that it's a good thing to do.
If you want to use a prefix on your ivar and method names, use anything but a single leading underscore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With