Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three Objective-C constructor questions

Tags:

objective-c

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,

like image 223
Andrew Grant Avatar asked Feb 02 '26 14:02

Andrew Grant


2 Answers

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.

like image 62
philsquared Avatar answered Feb 04 '26 03:02

philsquared


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;
}
like image 44
Rob Keniger Avatar answered Feb 04 '26 04:02

Rob Keniger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!