Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a custom initWith?

Tags:

objective-c

If I create a custom initWith for an object do I essentially include the code I would add should I want to override init?

-(id) init {
    self = [super init];
    if (self) {
        NSLog(@"_init: %@", self);
    }
    return(self);
}

e.g.

-(id) initWithX:(int) inPosX andY:(int) inPosY {
    self = [super init];
    if(self) {
        NSLog(@"_init: %@", self);
        posX = inPosX;
        posY = inPosY;
    }
    return(self);
}

gary

like image 955
fuzzygoat Avatar asked Nov 10 '09 21:11

fuzzygoat


3 Answers

You can create one designated initializer that accepts all parameters that you want to make available in initialization.

Then you call from your other -(id)init your designated initializer with proper parameters.

Only the designated initializer will initialize super class [super init].

Example:

- (id)init
{
    return [self initWithX:defaultX andY:defaultY];
}

- (id)initWithPosition:(NSPoint)position
{
    return [self initWithX:position.x andY:position.y];
}


- (id)initWithX:(int)inPosX andY:(int)inPosY
{
    self = [super init];
    if(self) {
        NSLog(@"_init: %@", self);
        posX = inPosX;
        posY = inPosY;
    }
    return self;
}

The designated initializer is -(id)initWithX:andY: and you call it from other initializers.

In case you want to extend this class you call your designated initializer from subclass.

like image 147
stefanB Avatar answered Nov 09 '22 21:11

stefanB


I'd suggest creating one main initializer that handles most of the work. You can then create any number of other initializers that all call this main one. The advantage of this is if you want to change the initialization process, you'll only have to change one spot. It might look like this:

-(id) initWithX:(float)x {
    if (self = [super init]) {
        /* do most of initialization */
        self.xVal = x;
    }
    return self;
}

-(id) init {
    return [self initWithX:0.0f];
}

In this example initWithX: is our main initializer. The other initializer (init) simply calls initWithX: with a default value (in this case 0).

like image 22
dbachrach Avatar answered Nov 09 '22 19:11

dbachrach


Yes, that's exactly how I do it. One slight change will cut out a line of code:

 if (self = [super init]) {

As opposed to:

 self = [super init];
 if(self) {
like image 33
Benjamin Cox Avatar answered Nov 09 '22 19:11

Benjamin Cox