The location of a variable declaration affects its scope, its lifetime, and the way in which you access it.
Common declaration types
Note that other types of declarations exist, these are the most common.
The following are descriptions of each type. Note that each example will use a variable of type NSArray named “arr” in a class named MyClass, a subclass of NSObject.
Scope: broadly, only the function in which it is declared Declaration and Usage:
- (void) myMythodName { NSArray*arr = [[NSArray alloc] init]; [arr.addObject:SOMEOBJECT]; }
Scope: the class in which the variable is declared. Not publically visible Accessing: use just the name of the variable Declaration: must be in curly braces in an @implementation section
Declaration (in a .m file):
@interface MyClass() { NSArray *arr; } @end
In a header file:
@interface MyClass : NSObject { NSArray *arr; } @end
Why are there two examples above? You can use @interface in the header file or the implementation file. The format is different for each (parenthesis in the .m file, the colon/superclass in the .h). The variable declared is the same.
Usage:
[arr addObject:SOMEOBJECT];
Scope: any class that uses the class, the class itself Accessing: Dot operator. Use self.NAME if accessing within class, OBJECT.NAME if using from another class Declaration: must be in header file outside of curly braces
Declaration (in a .h file):
@interface MyClass : NSObject { } @property (strong, nonatomic) NSArray *arr; @end
Usage:
[self.arr addObject:SOMEOBJECT];
What do properties do? They seem magical, but its actually quite simple. There aren't actually any public variables, variables declared with @property are replaced at compile time.
For example,
@property (strong, nonatomic) NSArray *arr;
is replaced with:
- (NSarray*) getArr; - (void) arr;
To recap: properties are a shorthand way of creating a private instance variable that has the same name as the property with an underscore and getter/setter methods. You should not refer to the underscored variable in code, although you can.
If you want to use the actual name of the variable instead of self.arr, include the following line after @implementation in the source code file:
@synthesize arr;
This allows you to use
[arr addObject:SOMEOBJECT];
instead of
[self.arr addObject:SOMEOBJECT];