As an Objective-C beginner, I’m very confused about the init function, and how and when to override it. So here are few questions :
- Apparently, it works fine when the init function is not overridden, so is it just a good practice to do it? If it is, then is it a very bad practice not to do it?
- Let’s assume I’m overriding the function because I have to assign a default value to a variable. Do I have to allocate and initialize all the other ivars, including IBOutlets?
Please note I’m aware of the syntax :
if ((self = [super init]))
{
_foo = [[Bar alloc] init];
}
return self;
Per “Initialization”:
As this says, you override your superclass’s designated initializer when you need to do some initialization after it’s done with its initialization. Don’t need to do that? Then you don’t need to override.
When your object is instantiated from a NIB,
-initis not called. Instead, your newly allocated object will receive an-initWithCoder:or-initWithFrame:message depending on the object’s type. The NIB loading process sends your object-awakeFromNibafter it and all the other NIB-created objects it references have been established. This lets you avoid overriding-initWithCoder:/-initWithFrame:when you wish to do some configuration after the NIB has been loaded. If you can do what you want to do by overriding-awakeFromNibrather than an initializer, you should do that.See also “Multiple Initializers”, which explains the “designated initializer” concept and how different classes can have different designated initializers, and “Allocating and Initializing Objects” for a less friendly but more in-depth description of the allocation and initialization conventions adopted by Objective-C.