OC中Runtime super关键字

在平时的开发过程中,我们经常会执行[super xxx]来调用父类的方法,但是我们很少会去关心super关键字的底层是如何实现的,接下来我们来看下super关键字底层实现原理,我们新建一个工程,然后创建Person类和Student类,Student类继承自Person类,示例代码如下:

Person

@interface Person : NSObject

- (void)run;
@end


@implementation Person

- (void)run {
    NSLog(@"%s", __func__);
}
@end

Student

@interface Student : Person

@end


@implementation Student

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

- (void)run {
    [super run];
    
    NSLog(@"%s", __func__);
}
@end

main函数:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        Student *stu = [[Student alloc] init];
        [stu run];
    }
    return 0;
}

接下来我们执行命令xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc -fobjc-arc -fobjc-runtime=ios-8.0.0 Student.mStudent.m文件转换为底层c++文件,转换为底层的run方法代码如下:

static void _I_Student_run(Student * self, SEL _cmd) {
    ((void (*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("Student"))}, sel_registerName("run"));

    NSLog((NSString *)&__NSConstantStringImpl__var_folders_lr_81gwkh751xzddx_ffhhb5_0m0000gn_T_Student_18b3ae_mi_0, __func__);
}

我们将Studnnt类的run方法进行简化如下:

- (void)run {
    [super run];
    
    /**
     结构体objc_super包含两个成员:
     self:消息接收者(receiver)
     class_getSuperclass(objc_getClass("Student")):消息接收者的父类(super_class)
     */
    struct objc_super superStruct = {
        self,
        class_getSuperclass(objc_getClass("Student"))
    };
    
    objc_msgSendSuper(superStruct, sel_registerName("run"));
    
    NSLog(@"%s", __func__);
}

我们发现当我们在run函数中执行[super run]后,最终底层转换为objc_msgSendSuper()消息发送,我们通过底层源码看下objc_msgSendSuper函数的定义,查找路径objc4 -> message.h -> objc_msgSendSuper,具体底层函数定义如下:

/**
 * Sends a message with a simple return value to the superclass of an instance of a class.
 *
 * @param super A pointer to an \c objc_super data structure. Pass values identifying the
 *  context the message was sent to, including the instance of the class that is to receive the
 *  message and the superclass at which to start searching for the method implementation.
 * @param op A pointer of type SEL. Pass the selector of the method that will handle the message.
 * @param ...
 *   A variable argument list containing the arguments to the method.
 *
 * @return The return value of the method identified by \e op.
 *
 * @see objc_msgSend
 */
 
OBJC_EXPORT id _Nullable
objc_msgSendSuper(struct objc_super * _Nonnull super, SEL _Nonnull op, ...)
    OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0);

我们从源码objc_msgSendSuper函数定义可以看到,函数接受两个参数

  • objc_super
  • SEL

我们再来看下objc_super结构体底层定义如下:

/// Specifies the superclass of an instance. 

struct objc_super {
    /// Specifies an instance of a class.
    
    // 消息接收者
    __unsafe_unretained _Nonnull id receiver;

    /// Specifies the particular superclass of the instance to message. 
#if !defined(__cplusplus)  &&  !__OBJC2__
    /* For compatibility with old objc-runtime.h header */
    __unsafe_unretained _Nonnull Class class;
#else

    // 消息接收者的父类
    __unsafe_unretained _Nonnull Class super_class;
#endif
    /* super_class is the first class to search */
};

简化objc_super结构体如下:


/**
 从`objc_msgSendSuper`函数的注释可以看到结构体的两个成员含义:the instance of the class that is to receive the message and the superclass at which to start searching for the method implementation.
 */
 
struct objc_super {
    // receiver就是消息接收者 (the instance of the class that is to receive the message)
    __unsafe_unretained _Nonnull id receiver;

    // super_class就是消息接收者的父类 (官方解释:the superclass at which to start searching for the method implementation)
    __unsafe_unretained _Nonnull Class super_class;
};

通过objc_super底层定义,我们可以看到这个结构体也包含两个成员

  • receiver
  • super_class

我们通过objc_msgSendSuper函数底层定义的注释中可以查看到参数objc_super结构体中两个成员的具体含义和作用

instance of the class that is to receive the message and the superclass at which to start searching for the method implementation

从上面注释我们了解到receiver就是消息的接受者(也就是方法调用者),superclass就是指从父类开始查找方法

因此在Studentinit初始化函数中打印结果如下:

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

classsuperclass函数的底层源码实现:

- (Class)class {
    // self为方法调用者,也就是消息接收者(receiver),返回当前方法调用者的类对象
    return object_getClass(self);
}
- (Class)superclass {
    // self为方法调用者,也就是消息接收者(receiver),返回当前方法调用者的父类对象
    return return self->superclass;
}

讲解示例Demo地址:https://github.com/guangqiang-liu/07.2-RunTimeSuper

更多文章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,527评论 5 470
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,314评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,535评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,006评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,961评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,220评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,664评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,351评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,481评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,397评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,443评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,123评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,713评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,801评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,010评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,494评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,075评论 2 341