Graphics Programs Reference
In-Depth Information
Other initializers and the initializer chain
A class can have more than one initializer. First, let's consider a hypothetical example.
BNRItem could have an initializer that takes only an NSString for the itemName . Its
declaration would look like this:
- (id)initWithItemName:(NSString *)name;
In this initializer's definition, you wouldn't replicate the code in the designated initializer.
Instead, this initializer would simply call the designated initializer, pass the information it
was given as the itemName , and pass default values for the other arguments.
- (id)initWithItemName:(NSString *)name
{
return [self initWithItemName:name
valueInDollars:0
serialNumber:@""];
}
Using initializers as a chain like this reduces the chance for error and makes maintaining
code easier. For classes that have more than one initializer, the programmer who created
the class chooses which initializer is designated. You only write the core of the initializer
once in the designated initializer, and other initialization methods simply call that core
with default values.
Now let's look at a real example. BNRItem actually has another initializer, init , which
it inherits it from its superclass NSObject . If init is sent to an instance of BNRItem ,
none of the stuff you put in the designated initializer will be called. Therefore, you must
link BNRItem 's implementation of init to its designated initializer.
In BNRItem.m , override the init method to call the designated initializer with default
values for all of the arguments.
- (id)init
{
return [self initWithItemName:@"Item"
valueInDollars:0
serialNumber:@""];
}
The relationships between BNRItem 's initializers (real and hypothetical) are shown in
Figure 2.14 ; the designated initializers are white, and the additional initializer is gray.
Figure 2.14 Initializer chain
 
Search WWH ::




Custom Search