In OO programming, using setters and getters is a very common and useful pattern. But writing these methods manually can be really time consuming.
To avoid that, Objective C use the concept of properties.
How to create a property :
@interface myObject : NSObj {
NSString* var1;
int var2;
}
@property(nonatomic,retain) NSString* var1;
@property(nonatomic,assign) int var2;
As you can see we use @property outside of the @interface block. The format is :
@property(options) type var.
The type and the name of the variable must be the same than in the @interfaceblock.
Several options are available to customize the behavior of a property.
The option atomic guarantee that the setter will be called in one atomic operation, this is useful when a property can be modified by more than one thread.
With nonatomic, you don’t have this guarantee. It can be compared to the@synchronized block which guarantee an atomic operation but slower.
The retain option will increment the reference counter when the getter is called (do a retain). The opposite is assign and will just assign the new value to the variable.
We can’t do a retain on a primitive data type, that’s why we use the assign option.