Introduction to Properties in Objective-C

Properties in Objective-C allow you to provide a well-defined interface for other classes to manipulate (i.e. get or set) attributes of a class. They also insulate external classes from the implementation details of the attributes (this separation of function and implementation is known as encapsulation).

To add a property to a class you need two parts:

  1. A property declaration
  2. An implementation or synthesis of a getter and/or setter method

The property declarations go in the interface section of your class:

The general form a property declaration is:
@property (attributes) type name;
Where attributes is a comma separated list. Attributes fall into a few categories:
Writability

readwrite
the property may be written and read. This is the default.
readonly
the property may only be read.

Setter Semantics

assign
the incoming value will be assigned to the property. Use this for plain datatypes (e.g. int, double).
reatain
the incoming value will be retained. If the value is an Objective-C object this is the most common.
copy
the incoming value will be copied. This is used if there is a chance that the incoming object may change (e.g. NSMutableString).
Atomicity

nonatomic
properties are atomic by default. Use this to avoid locking.

The compiler can automatically generate (synthesis) the most common forms of getters and setter for you. You instruct it to do so using the @synthesize directive in the implementation section of your class.

The general form of the synthesize directive is:
@synthesize property_name [ = instance_variable];
In the above the square brackets indicate an optional portion. In my case the name the instance variable used to store the property was not the same as the property so I need to specify it. Had I, for example, called the mFontSize instance variable fontSize then writing @synthesize fontSize; would have been sufficient. I’ll explain why you might want adopt a naming convention for instance variable in a later post.

Reference
The Objective-C Programming Language: Declared Properties

About idz

A professional software engineer dabbling in iOS app development.
This entry was posted in Objective-C. Bookmark the permalink.

2 Responses to Introduction to Properties in Objective-C

  1. pddro says:

    Awesome. Really helpful! I’m just starting to get into programmin. I’ve never done ANY programming. Nada. With these tuts, I’m getting better pretty quickly.

    Thanks!

Leave a Reply