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,
Just to add a little more to the three replies ahead of me:
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).
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With