tags:

views:

77

answers:

4

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

  • Does [super init] need to be done all the way down to NSObject? (e.g if Foo inherits from NSObject, should Foo call [super init]? If not, does that hold for dealloc too?
  • Does any form of default-initialization occur for member variables in an object. E.g would an NSString* member be initialized to nil? float to 0.0?
  • If my object has an initFoo method, can I call [self init] within that function to perform common initialization?

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,

A: 
  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
cobbal
+2  A: 

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;
}
Rob Keniger
A: 
  • 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.

Chris Becke
+4  A: 

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.

Phil Nash