Nimrod
Nimrod

Reputation: 5133

What's the correct way to perform initialization code whether an object is loaded from a nib or created programmatically?

I've noticed that if you load connected views from a nib you have to override initWithCoder if you want to add initialization code because the designated initializer doesn't get called (which does make sense), and if you don't load the view from a nib then the same code needs to be executed in the designated initializer.

So in order to handle both cases, you need the same initialization code in both methods.

This is the best solution that I have come up with so far, but I have to wonder if there's some more conventional way of doing this. This code is in a UITableViewCell subclass but it could be any UIView really:

/*
 * Seems like there should be a standard method for this already.
 */
- (void)didFinishInitializingOrUnacrhiving {
    /*** Do stuff that makes the most sense to do in an initializer. ***/
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self didFinishInitializingOrUnacrhiving];
    }
    return self;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self didFinishInitializingOrUnacrhiving];
    }
    return self;
}

So any thoughts on this? Is this the "right way" to do things, are there potential pitfalls here, or am I just totally missing something?

Upvotes: 4

Views: 1432

Answers (2)

Mark
Mark

Reputation: 6128

I explained this in another answer see Does interface builder use the init method to initialize view controllers?

Upvotes: 2

Thomas Müller
Thomas Müller

Reputation: 15635

I do exactly the same thing, except that I'm lazy and my method is usually called -didInit.

Upvotes: 1

Related Questions