Prefixing property names with an underscore in Objective C

Viewed 24458

I've previously avoided underscores in my variable names, perhaps a holdover from my college Java days. So when I define a property in Objective C this is what I naturally do.

// In the header
@interface Whatever
{
    NSString *myStringProperty
}

@property (nonatomic, copy) NSString *myStringProperty;

// In the implementation
@synthesize myStringProperty;

But in almost every example it is done like

// In the header
@interface Whatever
{
    NSString *_myStringProperty
}

@property (nonatomic, copy) NSString *myStringProperty;

// In the implementation
@synthesize myStringProperty = _myStringProperty;

Should I get over my aversion to the underscore because that is the one way it should be done, is there a good reason for this style being the preferred one?

Update: With automatic property synthesis nowadays you can leave out the @synthesize and the result is the same as if you'd used

@synthesize myStringProperty = _myStringProperty;

which clearly shows you Apple's preference. I've since learned to stop worrying and love the underscore.

7 Answers

The naming convention for the instance variable prefixed by _ is now clearly stated by Apple in the "Coding Guidelines for Cocoa", after the revision of 2012-02-16, with its reason.

Make sure the name of the instance variable concisely describes the attribute stored. Usually, you should not access instance variables directly, instead you should use accessor methods (you do access instance variables directly in init and dealloc methods). To help to signal this, prefix instance variable names with an underscore (_), for example:

@implementation MyClass {
    BOOL _showsTitle;
}

If you synthesize the instance variable using a declared property, specify the name of the instance variable in the @synthesize statement.

@implementation MyClass
@synthesize showsTitle=_showsTitle;

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html#//apple_ref/doc/uid/20001284-BAJGIIJE

The lecture in iTunes U, iPhone App Development CS193p Fall 2011 taught by Paul Hegarty at Stanford University, also explains this convention.

http://itunes.apple.com/itunes-u/ipad-iphone-application-development/id473757255

I'm aware of that this question is asked quite a while ago, but I myself had the same question and wanted to share my findings.

Related