iOS [self class] 、 [self superclass]、 [super class] 、[super superclass] 几种情况对比

例子 新建一个父类、一个子类 Person SubPerson

在子类中打印 

#import "SubPerson.h"
#import <objc/message.h>

@implementation SubPerson
-(void)test{
    NSLog(@"%@",[self class]); // SubPerson
    NSLog(@"%@",[self superclass]); // Person
    NSLog(@"%@",[super class]); // SubPerson
    NSLog(@"%@",[super superclass]); //Person
}

/*
 [super test]的底层实现
 1.消息接收者仍然是子类对象
 2.从父类开始查找方法的实现
 */

struct objc_super {
    __unsafe_unretained _Nonnull id receiver; // 消息接收者
    __unsafe_unretained _Nonnull Class super_class; // 消息接收者的父类
};

// super调用的receiver仍然是SubPerson对象
[super test];
struct objc_super arg = {self, [Person class]};
objc_msgSendSuper(arg, @selector(test));


@end

// NSObject 返回 class,superclass的伪代码
@implementation NSObject

-(Class)class{
    objc_getClass(self);
    
}
-(Class)superclass{
    class_getSuperclass(objc_getClass(self));
}
@end

在子类中调用 在父类中打印

#import "SubPerson.h"

@implementation SubPerson
-(void)test{
    [super test];
}
@end

 原理分析  [super class] 其实也是给当前对象发送一个class 消息 只是从父类开始查找 因为class 消息是NSobject的 直接返回了当前调用者的类型 所以 [super class] = [slef class]

原文地址:https://www.cnblogs.com/ZhangShengjie/p/12389705.html