Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between properties and variables in iOS header file? [duplicate]

Tags:

Possible Duplicate:
Is there a difference between an “instance variable” and a “property” in Objective-c?
Difference between self.ivar and ivar?

What is the difference between declaring variables in brackets immediately after the @interface line, and defining properties below?

For example...

@interface GCTurnBasedMatchHelper : NSObject { BOOL gameCenterAvailable; BOOL userAuthenticated; }  @property (assign, readonly) BOOL gameCenterAvailable; 
like image 278
Alan Avatar asked Mar 14 '12 12:03

Alan


1 Answers

Defining the variables in the brackets simply declares them instance variables.

Declaring (and synthesizing) a property generates getters and setters for the instance variable, according to the criteria within the parenthesis. This is particularly important in Objective-C because it is often by way of getters and setters that memory is managed (e.g., when a value is assigned to an ivar, it is by way of the setter that the object assigned is retained and ultimately released). Beyond a memory management strategy, the practice also promotes encapsulation and reduces the amount of trivial code that would otherwise be required.

It is very common to declare an ivar in brackets and then an associated property (as in your example), but that isn't strictly necessary. Defining the property and synthesizing is all that's required, because synthesizing the property implicitly also creates an ivar.

The approach currently suggested by Apple (in templates) is:

Define property in header file, e.g.:

@property (assign, readonly) gameCenter; 

Then synthesize & declare ivar in implementation:

@synthesize gameCenter = __gameCenter; 

The last line synthesizes the gameCenter property and asserts that whatever value is assigned to the property will be stored in the __gameCenter ivar. Again, this isn't necessary, but by defining the ivar next to the synthesizer, you are reducing the locations where you have to type the name of the ivar while still explicitly naming it.

like image 87
isaac Avatar answered Sep 22 '22 21:09

isaac