O'Reilly logo

Programming iOS 4 by Matt Neuburg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required