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:
- A property declaration
- An implementation or synthesis of a getter and/or setter method
The property declarations go in the interface section of your class:
@interface RootViewController : UITableViewController { CGFloat mFontSize; NSArray* mFontNames; } @property (nonatomic, assign) CGFloat fontSize; @property (nonatomic, retain) NSArray* fontNames; @end
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).
- nonatomic
- properties are atomic by default. Use this to avoid locking.
-
Atomicity
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.
@implementation RootViewController @synthesize fontSize = mFontSize; @synthesize fontNames = mFontNames; // Rest of implementation @end
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
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!
Cool! Glad you are finding them useful. I hope to have some new tutorials soon.
Cheers,
idz