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 :
Please note I'm aware of the syntax :
if ((self = [super init]))
{
_foo = [[Bar alloc] init];
}
return self;
Per "Initialization":
A class generally implements an initializer for its objects, but is not required to. If a class does not implement an initializer, Cocoa calls the initializer of the nearest ancestor of the class. However, subclasses often define their own initializer or override an initializer of their superclass to add class-specific initializations. If a class does implement an initializer, it should invoke an initializer of its superclass as the first step. This requirement ensures a series of initializations for an object down the inheritance chain, starting with the root object. The
NSObjectclass declares theinitmethod as the default object initializer, so it is always invoked last but returns first.
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, -init is 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 -awakeFromNib after 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 -awakeFromNib rather 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.
There is no need to override -init (or the designated initializer) unless you need to do class-specific initialization.
You do not need to (nor should you) allocate or initizlize IBOutlets. Objective-C will automatically initialize all instance variables including IBOutlets to 0 (nil).
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