Properties

A property is a syntactical feature of Objective-C 2.0 designed to provide an alternative to the standard syntax for calling an instance variable accessor. In other words, a property is merely syntactic sugar for calling an instance variable’s accessors. I’ll use the Dog class as an example. If the Dog class has an instance variable number and a getter method called number and a setter method called setNumber:, then the Dog class might also declare a number property. If it does, then instead of saying things like this:

[fido setNumber: 42];
int n = [fido number];

You can talk like this:

fido.number = 42;
int n = fido.number;

As you can see, this is a very pleasant syntax. You use dot-notation to chain the property name to the instance, and you can use the resulting expression either on the left side of an equal sign (to set the instance variable’s value) or elsewhere (to fetch the instance variable’s value). Remember, though, that you can do this only if the class you’re talking to has declared a property corresponding to the instance variable in question. Remember also that your use of property syntax is not compulsory. If Dog has a number property, it has getter and setter methods number and setNumber:, and you are free to call them directly if you like. When you use a property in code, it is translated behind the scenes into a call to the corresponding getter or setter method, so it’s all the same if you call the corresponding getter or setter method explicitly.

To use ...

Get Programming iOS 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.