Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-c: Questions about self = [super init]

Tags:


I have seen self = [super init] in init methods. I don't understand why. Wouldn't [super init] return the superclass? And if we point self = [super init], are we not getting self = superclass?
Here's an example code fragment

- (id)init  {     if (self = [super init]) {         creationDate = [[NSDate alloc] init];     }     return self; } 

Hope someone can clarify this for me. Thank you.

like image 929
CodeHelp Avatar asked Sep 09 '13 07:09

CodeHelp


People also ask

Why self super init?

Why do we assign [super init] to self here? The textbook reason is because [super init] is permitted to do one of three things: Return its own receiver (the self pointer doesn't change) with inherited instance values initialized. Return a different object with inherited instance values initialized.

What is super in Objective C?

Super is self , but when used in a message expression, it means "look for an implementation starting with the superclass's method table."

Is super init necessary?

In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class ( dict ).

What is Alloc and init in Objective C?

Alloc allocates memory for the instance, and init gives it's instance variables it's initial values. Both return pointers to the new instance, hence the method chain.


1 Answers

Assuming that MyClass is a subclass of BaseClass, the following happens when you call

MyClass *mc = [[MyClass alloc] init]; 
  1. [MyClass alloc] allocates an instance of MyClass.
  2. The init message is sent to this instance to complete the initialization process.
    In that method, self (which is a hidden argument to all Objective-C methods) is the allocated instance from step 1.
  3. [super init] calls the superclass implementation of init with the same (hidden) self argument. (This might be the point that you understood wrongly.)
  4. In the init method of BaseClass, self is still the same instance of MyClass. This superclass init method can now either

    • Do the base initialization of self and return self, or
    • Discard self and allocate/initialize and return a different object.
  5. Back in the init method of MyClass: self = [super init] is now either

    • The MyClass object that was allocated in step 1, or
    • Something different. (That's why one should check and use this return value.)
  6. The initialization is completed (using the self returned by the superclass init).

So, if I understood your question correctly, the main point is that

[super init] 

calls the superclass implementation of init with the self argument, which is a MyClass object, not a BaseClass object.

like image 136
Martin R Avatar answered Oct 13 '22 06:10

Martin R