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 what 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 propertysaleto the ivar_saleusing 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.saleequal to an autoreleased NSString would be fine since it would get retained, but setting_saleequal 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.