Let’s start with a piece of code:


@interface Person : NSObject
@end
@implementation Person
@end

@interface Son : Person
@end
@implementation Son

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSLog(@ "% @"[self class]);
        NSLog(@ "% @"[super class]);
    }
    return self;
}

@end

// Print the result:Son Son is SonCopy the code

Using the clang-rewrite-objc command, the resulting intermediate code has the following key parts:

(void *)objc_msgSend)((id)self, sel_registerName("class")

(void *)objc_msgSendSuper)((__rw_objc_super){ (id)self, (id)class_getSuperclass(objc_getClass("Son"))},sel_registerName("class")
Copy the code

The difference between [self class] and [super class] is: The only difference between objc_msgSend(id, SEL) and objc_msgSendSuper(__rw_objc_super *superclass, SEL) is the starting point of the lookup method. The former is the current class Son, while the latter is the parent class Person.

Objc_msgSendSuper will eventually become objc_msgSend((id)self, sel_registerName(“class”)).

That’s just the normal messaging-sending process, where Son starts looking for the class method, and Person starts looking for the parent class, and since neither of them has a class method, both go to the base class NSObject, and both call the base class class method.

Runtime runtime runtime runtime

// NSObject.mm
-(Class)class { 
  return object_getClass(self); 
}

// objc-class.mm
Class object_getClass(id obj)
{
    if (obj) return obj->getIsa(a);else return Nil;
}

Copy the code

So, both are actually going to find the class object that self’s isa pointer points to, which is Son. Super is just a compilation instruction, but the message receiver is still self, which is the instance object of the current class.

  • In addition, why do objects need to be initializedself = [super init]?

Call the init method of the parent class, and bring the parent class’s initialization data, write it to the memory of the current class, and pass it to the instance object of the current class.