I have been working with Objective C for a few months now and feel like I maybe know 1% of it, and understand even less than that…
Regardless, I have two moderately popular games out, and learning more every day.
When I first started, I learned that the method of defining properties was to use the same identifier for the property and the instance variable, as follow:
code.h:
@interface MyClass : UISomething {
NSString *myPropName;
}
@property (nonatomic, retain) NSString *myPropName;
@end
code.m
@synthesize myPropName;
Recently I saw the following used, where the instance variable is named differently than the property, and then the property is set to the instance variable in the implementation:
code.h:
@interface MyClass : UISomething {
NSString *_myPropName;
}
@property (nonatomic, retain) NSString *myPropName;
@end
code.m:
@synthesize myPropName = _myPropName;
Is there a reason for not using same identifier for the property and instance variable?
Thanks!
Hanaan
Not really. Some people like the convention of prefixing the instance variables with an underscore. (Seems pointless to me.) Other people like to change the property names for boolean variables:
You might also want to use a shorter identifier for the instance variable and more descriptive name for the property (
audioPlayer = player). And one final application comes to mind, renaming variables in combination with protocols:Here it’s beneficial to rename the variable as you are only providing access to one of its facets.