Is it really necessary to call init
after object allocation? I mean: in Java for instance if you don't call it (the constructor), it will be called anyway (the default constructor). In Objective C you can create an alternative constructor (like Java) and one of the things I see the most is self = [super init]
. I read: cocoawithlove article, but in the end it's not clear why we should make such assignment self = [super init]
. It just says that the [super init]
can return a different object, and then we must replace the self
with that new object. That wouldn't explain why we do it in first place.
Out of the box in Objective-C you can initialize an instance of a class by calling alloc and init on it. // Creating an instance of Party Party *party = [[Party alloc] init]; Alloc allocates memory for the instance, and init gives it's instance variables it's initial values.
Whenever an object is "created" by default it is supposed to be done with myObject=[[MyObjectClass alloc]init] or the equivalent shortcut myObject=[MyObjectClass new] . That is where your init method is called.
init() Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.
is it really necessary to call init after object allocation?
Yes, it is necessary. To compare to Java, calling [super init]
(or some other designated initializer) effectively runs the superclass' constructor. This mechanism is provided for you in Java, but not in Objective-C. So it is not called implicitly in ObjC as it is in Java. In ObjC, you must call one of the superclass' designated initializers explicitly. If you do not call your superclass' initializer, your object will not be entirely initialized. This may result in no exhibited side-effects, or it could result in a completely unusable object which invokes undefined behavior.
why we should make such assignment self = [super init].
Right, alloc
creates an allocation (with zeroed memory) and sets the pointer to the class information isa
, but a superclass' initializer permits the superclass to exchange the instance with another which may be more appropriate. Typically, you would avoid doing this in your own subclasses. The other reason to perform this and the nil check is that it is the means an error is handled. In ObjC, exceptions are generally non-recoverable, so the conventional way to report an error to the subclass is to return nil
. That is why it is also important not only to assign self
, but also to test it for 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