1) @property is a special way to define getter- and setter-methods, or as we call them accessors in Objective-C. Your first snippet just declares an array for which you have to declare and write accessors yourself. For example setMyArray:
and myArray
.
Using @property will declare your accessors for you and is equivalent to declaring setMyArray:
and myArray
yourself. It is the preferred way to declare accessors since Objective-C 2.0. Note that you still have to declare the property (in your case myArray) yourself.
2) You first need to know about @synthesize. Remember that @property DECLARES the accessors for your property, @synthesize will IMPLEMENT them. When you use an @property in your @interface you mostly likely write an @synthesize in @implementation. Using @synthesize is equivalent to implementing setMyArray:
and myArray
.
The attributes (nonatomic, retain)
tell the compiler, among others, how the memory management should work and therefore how the methods will be implemented. Note that you never actually see these accessors, but be assured that they are there and ready for you to be used.
To read more on that topic I recommend reading Section 9 on Properties from the following Tutorial or buy a Book that covers an Introduction to Objective-C.
Also you should familiarize yourself with at least the following attributes:
- Access
- Choose
readwrite
(default) or readonly
. If readonly
is set, ONLY the getter methods will be available.
- Setter Memory Management
assign
(default), simply assigns the new value. You mostly likely only use this with primitive data types.
retain
, releases the old value and retains the new. If you use the garbage collector, retain
is equivalent to assign
. Why? The manual release of the old value will be done by the garbage collector.
copy
will copy the new value and release the old value. This is often used with strings.
- Threading
atomic
(default) will ensure that the setter method is atomic. This means only one thread can access the setter at once.
nonatomic
, use this when you don't work with threads.
This post gives you a good introduction to memory management and assign
, retain
and copy
.