views:

150

answers:

2

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?

+1  A: 

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

Thomas Müller
+1  A: 

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

Mark Thalman
Thanks. I was hoping someone might know more about what the issues might be when doing each. Do you know if there are any good documents or discussions that sort of explain the issues with regard to initialization vs. dearchiving? I mean the basic issue is that archived objects are already initialized and thus shouldn't be re-initialized from scratch as that would normally defeat the whole purpose of archiving. What about non-nib files? Is there a more generic awakeFromDecoding or something? Or is overriding initWithCoder essentially just that?
Nimrod
The Apple documentation is a great place to start, although a bit terse at times. Sometimes not knowing what you are looking for can be a problem. http://bit.ly/9iPNgbinitWithCoder is for initialization during decoding. Note that in this override the outlets and actions are not guaranteed to be connected, but with awakeFromNib they are.A good starting point for Cocoa programming is "Cocoa Programming for Mac OS X" by Aaron Hillegass. He covers this topic and many others. Also he's a nice guy. If you can afford it, or convince your employer his classes at Big Nerd Ranch are excellent.
Mark Thalman