Domanda

I am having some trouble understanding designated initializers. I am studying Objective C from the book "Learn Objective C on the Mac". The following is an implementation file.

#import "Tire.h"


@implementation Tire

- (id) init
{
    if (self = [self initWithPressure: 34 treadDepth: 20]) {
    }

    return (self);

} // init


- (id) initWithPressure: (float) p
{
    if (self = [self initWithPressure: p treadDepth: 20.0]) {
    }

    return (self);

} // initWithPressure


- (id) initWithTreadDepth: (float) td
{
    if (self = [self initWithPressure: 34.0 treadDepth: td]) {
    }

    return (self);
} // initWithTreadDepth


- (id) initWithPressure: (float) p treadDepth: (float) td
{
    if (self = [super init]) {
        pressure = p;
        treadDepth = td;
    }

    return (self);
} // initWithPressure:treadDepth:

From what I understand:

- (id) initWithPressure: (float) p treadDepth: (float) td

is the default initializer. When an instance of the Tire class shall be initialized with a statement like

Tire *aTire = [[Tire alloc] init];

then the above mentioned initialization method will be executed. However, since the method contains "pressure = p", what is pressure equal to since until this stage we have not given "p" any value. Also, what happens after this method finishes execution? Which is the next "init" method in queue?

È stato utile?

Soluzione

init in Tire class method calls [self initWithPressure: 34 treadDepth: 20] so pressure will be 34.

Next method in the chain will be init method from super-class, because initWithPressure: (float) treadDepth: (float) method explicitly calls it: [super init].

After initWithPressure: (float) treadDepth: (float) finishes, execution continues from the point where initWithPressure... was called.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top