A property (see Chapter 5) is syntactic sugar for calling an accessor by using dot-notation. An object does not have a property unless its class (or that class’s superclass, of course) declares it. For instance, in a earlier example we had an object with an NSMutableArray instance variable and a setter, which we called like this:
[self setTheData: d];
If this object’s class code declares a property
theData, we could instead say:
self.theData = d;
The effect would be exactly the same, because setting a property is just a shorthand for calling the setter. Similarly, suppose we were to say this:
NSMutableArray* arr = self.theData;
That is exactly the same as calling the getter.
Properties offer certain advantages that accessors, of themselves, do not:
- It is simpler to declare one property than to declare two accessor methods.
- A property declaration includes a statement of the setter’s memory management policy. Thus it easy to know, just by glancing at a property declaration, how the incoming value will be treated. You could find this out otherwise only by looking at the setter’s code — which, if this is a built-in Cocoa type, you cannot do (and even in the case of your own code, it’s a pain having to locate and consult the setter directly).
- With a property declaration, you can ask Cocoa to construct the accessors for you, automatically. Such an automatically constructed accessor is called a synthesized accessor. Writing accessors is boring and error-prone; with a property, you ...