Defining members and properties in Xcode 4 & iOS 4
I am fairly far along developing a reasonably ambitious first iPhone project and I am confused as to which way to implement and access properties and why.
Example 1: (in the .h)
Nsstring *_sale;
@property (nonatomic, retain) NSString *sale;
(in the .m)
@synthesize sale = _sale;
Example 2: (in the .h)
@property (nonatomic, retain) NSString *sale;
(in the .m)
@synthesize sale;
Both of these seem to work to me without trouble but I am trying to figure out why there are two ways to do this and wha开发者_如何转开发t benefits there may be to either.
Can someone tell me the difference?
Example 1 demonstrates the old way of defining ivar/property variable pairs. The new compiler now generates ivars (the NSstring *_sale;
part) for you. Example 1 also demonstrates manually pairing up the property sale
to the ivar _sale
using the @synthesize sale = _sale;
statement.
Example 2 is a more concise way to implement properties in Obj-C and is the way you will see most example code on the internet. The vast majority of the time you can write your properties without needing to overwrite the accessor/mutator methods generated for you by the compiler.
There are some die-hard proponents of the underscore prefix to denote instance variables for clarity's sake. You may find that this helps you when it comes to memory management, as in Example 1, setting self.sale
equal to an autoreleased NSString would be fine since it would get retained, but setting _sale
equal to an autoreleased object would result in erratic behavior later on because the NSString passed in would not be retained by the instance variable.
In general, I prefer writing my properties as you have shown in Example 2.
Short Answer: There are two ways of doing this because the new compiler now can infer some stuff for you, but the previous way of doing things has been left in for backwards compatibility.
They both work the same way. Some people prefix their instance variable with an underscore as a visual cue to differentiate member variables from instance variables.
More discussion at this SO question: How does an underscore in front of a variable in a cocoa objective-c class work?
For more Cocoa style guidelines checkout CocoaDevCentral.
精彩评论