Andrew Grant
Andrew Grant

Reputation: 58804

Three Objective-C constructor questions

I have three quick questions I've seen conflicting answers to that hopefully someone can clear up.

Since starting with Objective-C I've pretty much assumed Yes for the first and No for the second two, but I'm hoping to save some typing :)

Thanks,

Upvotes: 3

Views: 522

Answers (4)

philsquared
philsquared

Reputation: 22493

Just to add a little more to the three replies ahead of me:

  1. Yes it does. In practice NSObject (probably) doesn't require it (now), but if that ever changed you're screwed if you haven't. It's best to get into the habit anyway (or use the code generation in XCode to drop an init template down). That said it's not always init that you should call (more soon).

  2. As has been noted initialisation to defaults (by virtue of memcpy 0s, so 0, nil, etc) is guaranteed and it's reasonably idiomatic to rely on this. Some people still prefer to be explicit and that's fine.

  3. Absolutely. Remember init, or any variation is just a normal method. It's only an initialiser by convention (albeit a very strong convention). You are free to call other methods, including other initialisers. Again, by convention, you should decide on a "designated initializer" and have all other initialisers call this. Think about this in relation to your first question. If you subclass, what will your subclass call? By default a subclass author will call your init - so if you have a different designated initializer then it is very important that you make that clear so subclass authors know to call it.

You can read more (authoritative) detail here in the Apple docs.

Upvotes: 6

Chris Becke
Chris Becke

Reputation: 36121

  • Yes, Otherwise the superclass objects wont get a chance to do their initialization.

  • don't know.

  • Yes. Create whatever init method you want. Document it. But be sure to call the super's proper init method: whatever it may be.

Upvotes: 0

Rob Keniger
Rob Keniger

Reputation: 46028

You always need to call the initialization method of the superclass and assign self to the result. You also definitely need to call super's implementation at the end of your implementation of -dealloc.

All instance variables are initialized to zero/nil by default, this is guaranteed.

Yes, you can call [self init] from a more specific initialization method:

- (id)initFoo
{
    self=[self init];
    if(self)
    {
       //do stuff
    }
    return self;
}

Upvotes: 2

cobbal
cobbal

Reputation: 70765

  1. yes for init (not technically required, but best practice) definitely yes for dealloc
  2. yes, all memory is initialized to 0 which is nil, 0.0, etc.
  3. yes, and this is common

Upvotes: 0

Related Questions