@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, High school drop-out. College drop-out. A go-go dancer in Amsterdam. LOVED computers, programmed satellites for AT&T. Founded IPSOFACTO in 1996, Y2K boom, Dot-Com boom, 2.0 boom. Likes his smallish company and human relationships; not into big anonymous IT. Loves to tell jokes. Loves and Hates technology; pick up the phone, ok? Thinks on line hook up sites have saved the world from AIDS and DateRape. Thinks his kids are better collaborators and world leaders thanks to video games. Is still a hip-hop dancer; is NOT a Brony. Loves San Francisco; Hates the homeless crisis. Tells young people to buy real estate, as soon as possible. Don’t rent. Hopes his final years are spent handing out blankets, food, clothes, and medical supplies.