0
votes

Well...I have read and have done a lot of research on the expression of [super init] in class inheritance of objective-c. Even some of the questions have been well explained and answered on stackoverflow. However, I still don't really understand how inheritance or the [super init] works.

In other languages, the superclass knows nothing about the subclass. There is no way for the superclass to return an object of the subclass because the superclass has no knowledge of the subclass. So my question is if expression self = [super init] return the object of the SUPERCLASS or SUBCLASS. Here I do know that the [super init] could return another object or nil, which makes sense. But assuming everything works fine and neither is it nil nor return another object. If it returns a regular object, does it return the object of the superclass or derived class, which is the class in which this self = [super init] is defined. If it returns an object of the super class, then it makes sense but then since as we know, the object of the superclass knows nothing about the subclass, how can it access the members (fields, messages or methods) of the subclass. If it returns an object of the subclass, then it does not make sense, since there is no way that the superclass can return an object of the derived class because the superclass knows nothing of it.

This is one of the aspects that is really confusing for those who transition from other languages to objective-C.

1

1 Answers

2
votes

self = [super init] will return the object from the superclass. However, note that the object itself has likely been allocated using alloc on your current class.

Consider the following:

@interface A : NSObject
- (instancetype)init;
@end

@interface B : A
- (instancetype)init;
@end

@implementation B
- (instancetype)init {
    self = [super init];
    if (self) {
        // Do initialization for B
    }
    return self;
}
@end

When you create a new object of a class B you do as follows:

B *obj = [[B alloc] init];

In turn the following happens:

  • [B alloc]allocates the object with enough space to hold all of B.
  • Calls init on the newly created object of class B.
  • Then init on class A is called from B's init method
  • init on class A will* return the object allocated with B's alloc.

*) Note that the init method may return another object than the allocated one. This is allowed, and is a reason why you usually should assign the result to self.

Read more - What does it mean when you assign [super init] to self?