Defining Members and Properties in Xcode 4 and iOS 4

I pretty far developed the rather ambitious first iPhone project, and I'm confused about how to implement and access properties and why.

Example 1: (in .h)

Nsstring *_sale; @property (nonatomic, retain) NSString *sale; 

(in .m)

 @synthesize sale = _sale; 

Example 2: (in .h)

 @property (nonatomic, retain) NSString *sale; 

(in .m)

 @synthesize sale; 

Both of these seem to work for me without any problems, but I'm trying to understand why there are two ways to do this and what benefits may be for them.

Can someone tell me the difference?

+4
source share
2 answers

Example 1 demonstrates an old way of defining pairs of ivar / property variables. The new compiler now generates ivars (part of NSstring *_sale; ) for you. Example 1 also demonstrates manually matching the sale property with ivar _sale using the @synthesize sale = _sale; .

Example 2 is a more concise way to implement properties in Obj-C, and this is how you will see most code examples on the Internet. The vast majority of the time, you can write your properties without overwriting the accessor / mutator methods that the compiler created for you.

There are some strong proponents of the underscore prefix to refer to instance variables for clarity. You may find that this helps you when it comes to memory management, as in Example 1, setting a self.sale equal to an autorexized NSString will be fine as it will be saved, but setting a _sale equal to an autorealized object will result in a more unstable behavior later because the passed NSString will not be saved by the instance variable.

In general, I prefer to write my properties, as shown in Example 2.

The short answer . There are two ways to do this, because the new compiler can now output some things for you, but the previous way to do everything has remained for backward compatibility.

+4
source

Both of them work the same way. Some people prefix their instance variable with an underscore as a visual signal to differentiate member variables from instance variables.

More discussions in this SO question: How is the underscore before a variable in the cocoa objective-c class emphasized?

For a more cocoa CocoaDevCentral style guide .

+2
source

All Articles