@property in Objective-C

@property in Objective-C

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.

The Apple documentation provide a full list of all available parameters.

Steve Boullianne, Multiple post-graduate degrees, Mind/Body/Spirit enthusiast, & a member of Mensa. Loves Skiing, Scuba, and Food. Steve’s First job out of college was programming satellites for AT&T. Founded IPSOFACTO in 1996, Y2K boom, e-Commerce super success, 2.1 boom. Steve is ready to Mediate high quality for all life, our one planet, and human kindness. Loves to dance and tell jokes. Steve believes that Excellent Communication is key to human success (and failure). Steve has 3 sons who are his STARS. They will carry the world into a brilliant future. Since 1996, Steve has been a volunteer drug and alcoholism counselor in the Bay Area. The power of the Great Spirit is in you. Steve is a good friend to have.