I've always avoided underscores in my variable names, perhaps because its just not what was done back in my learning Java in college days. So when I define a property in Objective C this is what I naturally do.
//in the header
@interface Whatever
{
NSString *myStringPorperty
}
@property (nonatomic, retain) NSString *myStringProperty;
//in the implementation
@synthesize myStringProperty;
But in almost every example it is done like
//in the header
@interface Whatever
{
NSString *_myStringPorperty
}
@property (nonatomic, retain) 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?
Current suggested Objective-C 2.0 practice is to use the same name for the ivar as the property. You can optionally assign a different ivar in the @property declaration, but the fact that by default, synthesized accessors for a property will access the ivar with the same name as the property indicates that's the pattern they expect you to follow.
No matter what, since objects still have to send messages to themselves to access properties, it's hard to confuse when you're accessing a property or when you're accessing its backing ivar directly, though using the 2.0 dot access to properties does make it more possible. Using the standard message passing syntax makes intent more explicit, IMO.
@interface Foo : NSObject {
NSNumber *bar;
}
@property(readwrite, retain) NSNumber * bar
@end
@implementation Foo
@synthesize bar
-(void) baz {
NSNumber *numberOne = [NSNumber numberWithInt: 1];
//Both set the value of bar through either the your custom or the synthesized setter method
[self setBar:numberOne];
self.bar = numberOne;
//Both get the value of bar through your synthesized or your custom accessor method
NSNumber *fooBar = [self bar];
fooBar = self.bar;
//Both manipulate the bar ivar directly
bar = numberOne;
fooBar = bar;
}
@end