Graphics Programs Reference
In-Depth Information
The synthesized setter won't include the second line establishing the reciprocal relation-
ship between the container and the containedItem . Its implementation just looks
like this:
- (void)setContainedItem:(BNRItem *)i
{
containedItem = i;
}
Because we need this setter to do additional work, we cannot rely on the synthesized
method and must write the implementation ourselves. Fortunately, writing our own imple-
mentation does not conflict with synthesizing the property. Any implementation we add
will override the synthesized version. In BNRItem.m , add back the implementation of
setContainedItem: .
- (void)setContainedItem:(BNRItem *)i
{
containedItem = i;
[i setContainer:self];
}
Build and run the application again. It should work the same as always, but your code is
much cleaner.
Synthesizing a property that you declared in the header file is optional, but typical. The
only reason not to synthesize a property is if both the getter and the setter methods have
additional behavior you need to implement.
Instance variables and properties
With properties, we can go even one step further in code clarity. By default, a synthesized
property will access the instance variable of the same name. For example, the itemName
property accesses the itemName instance variable: the itemName method returns the
value of the itemName instance variable, and the setItemName: method changes the
itemName instance variable.
If there is no instance variable that matches the name of a synthesized property, one is
automatically created. So declaring an instance variable and synthesizing a property is re-
dundant. In BNRItem.h , remove all of the instance variables as well as the curly brack-
ets.
@interface BNRItem : NSObject
Search WWH ::




Custom Search