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.