OC-Runtime-super关键字

image-20210507155714545

究一下super关键字,在讲之前我们先看一下下面四条语句输出打印什么

***********************🕴MJPerson.h 🕴**************************
#import <Foundation/Foundation.h>

@interface MJPerson : NSObject
- (void)run;
@end
    
***********************🕴MJPerson.m 🕴**************************        
#import "MJPerson.h"

@implementation MJPerson
- (void)run
{
    NSLog(@"%s", __func__);
}
@end
    
***********************🕴MJStudent.h 🕴**************************      
#import "MJPerson.h"

@interface MJStudent : MJPerson

@end
***********************🕴MJStudent.m 🕴**************************  
#import "MJStudent.h"
#import <objc/runtime.h>

@implementation MJStudent
- (instancetype)init
{
    if (self = [super init]) {
        NSLog(@"[self class] = %@", [self class]); // MJStudent
        NSLog(@"[self superclass] = %@", [self superclass]); // MJPerson

        NSLog(@"--------------------------------");

        NSLog(@"[super class] = %@", [super class]); // MJStudent
        NSLog(@"[super superclass] = %@", [super superclass]); // MJPerson
    }
    return self;
}

@end    
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        MJStudent *student = [[MJStudent alloc] init];
        
        
    }
    return 0;
}

RUN>

*********************** 👁运行结果👁 **************************
2021-05-07 16:03:26.690440+0800 Interview05-super[4285:175492] [self class] = MJStudent
2021-05-07 16:03:26.690907+0800 Interview05-super[4285:175492] [self superclass] = MJPerson
2021-05-07 16:03:26.690949+0800 Interview05-super[4285:175492] --------------------------------
2021-05-07 16:03:26.690973+0800 Interview05-super[4285:175492] [super class] = MJStudent
2021-05-07 16:03:26.690995+0800 Interview05-super[4285:175492] [super superclass] = MJPerson    
image-20210507160642347

我们看到[super class][super superclass]的打印结果不是我们所预期的。怎么回事呢?

要搞清楚这个问题我们就需要搞懂super关键字,class(),superClass()的底层,我们把Student.m转为c++代码看看底层是怎样的:

***********************🕴MJStudent.h 🕴**************************   
#import "MJPerson.h"

@interface MJStudent : MJPerson
- (void)run;
@end
***********************🕴MJStudent.m 🕴**************************  
#import "MJStudent.h"
#import <objc/runtime.h>

@implementation MJStudent
- (instancetype)init
{
    if (self = [super init]) {
        NSLog(@"[self class] = %@", [self class]); // MJStudent
        NSLog(@"[self superclass] = %@", [self superclass]); // MJPerson

        NSLog(@"--------------------------------");

        NSLog(@"[super class] = %@", [super class]); // MJStudent
        NSLog(@"[super superclass] = %@", [super superclass]); // MJPerson
    }
    return self;
}

- (void)run
{
    [super run];
    NSLog(@"MJStudet.......");
}
@end

转化为底层C++代码

xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc -fobjc-arc -fobjc-runtime=ios-8.0.0 MJStudent.m -o MJStudent-arm64.cpp

以看到run方法的底层实现如下

static void _I_MJStudent_run(MJStudent * self, SEL _cmd) {

    ((void (*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("MJStudent"))}, sel_registerName("run"));

    //[NSLog ]
    NSLog((NSString *)&__NSConstantStringImpl__var_folders_yh_qjzhl57s63j2m9l4frv27zjc0000gn_T_MJStudent_c2a994_mi_0);

}

简化一下

//
static void _I_MJStudent_run(MJStudent * self, SEL _cmd) {
    //👉👉👉[super run];
    objc_msgSendSuper((__rw_objc_super){
            (id)self,   
            (id)class_getSuperclass(objc_getClass("MJStudent"))
           },   
            @selector(run));
}

*************♥️♥️♥️再精简一下
static void _I_MJStudent_run(MJStudent * self, SEL _cmd) {
//⚠️⚠️⚠️结构体单独抽出来
struct __rw_objc_super arg = {
            (id)self,   
            (id)class_getSuperclass(objc_getClass("MJStudent"))
};

//👉👉👉[super run];
   objc_msgSendSuper(arg, @selector(run));
}

发现super底层被转换为objc_msgSendSuper(arg1,arg2)函数,里面传入连个参数__rw_objc_super 结构体和 SEL @selector(run)就是一个方法选择器SEL

那么__rw_objc_super是什么呢,我们在runtime源码中搜搜objc_super:

image-20210507162852053
//🤡🤡🤡objc源码中的定义🤡🤡🤡
/// 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 */
};
#endif

  • id receiver; —— 消息接受者,其实实参传递的就是self,也就是CLStudent的实例对象
  • Class super_class; —— 父类,通过中间码里面该结构体初始化的赋值代码

(id)class_getSuperclass(objc_getClass("MJStudent")可以看出,这个父类就是MJStudent的父类类对象[MJPerson class].

objc_super的底层就是消息的接受者和他的父类,结合这些底层知识我们把[super run]底层的c++代码修改一下:

    struct objc_super arg = {self, [MJPerson class]};

    objc_msgSendSuper(arg, @selector(run));

<font color='red'>super 方法的接受者仍然是子类,传入的父类是干嘛用的呢?</font>

接着我们在看一下objc_msgSendSuper里面究竟干了什么事情,我们在runtime源码中搜索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);
#endif

super—— 是一个指向结构体指针struct objc_super *,它里面的内容是{消息接受者 recv消息接受者的父类类对象 [[recv superclass] class]},objc_msgSendSuper会将消息接受者的父类类对象作为消息查找的起点。

原来 superclass 是为了告诉 runtime ,查找方法的时候直接从 superclass 的类中查找.❎不要在像以前那样通过 实例对象 isa 找到类对象,从类对象的方法列表中查找,如果找不到再通过类对象的 superclass 找到父类从父类的方法列表中查找.❎

[super message]的底层实现

1.消息接收者仍然是子类对象

2.从父类开始查找方法的实现

  • 为了加深理解,我们对比一下给对象正常发送消息后的查找流程

[obj message]->在obj的类对象cls查找方法->在cls的父类对象[cls superclass]查找方法->在更上层的父类对象查找方法-> **...** ->在根类类对象 NSObject里查找方法`

[super message] -> 在obj的类对象cls查找方法(跳过此步骤) -> (直接从这一步开始)在cls的父类对象[cls superclass]查找方法 -> 在更上层的父类对象查找方法 -> ... -> `在根类类对象 NSObject里查找方法

  • class方法的底层:
//class 底层实现
- (Class)class{
    return object_getClass(self);//获取方法接受者的类对象或者元类对象
   // object_getClass底层调用的 getIsa(),如果是实例对象获取的就是类对象,如果是类对象获取的就是元类对象.
}
  • superClass方法的底层:
// superclass 底层实现
- (Class)superclass{
    //先获取方法接受者的类对象
    //在获取它的父类对象
    return class_getSuperclass(object_getClass(self));
}
NSLog(@"[self class] = %@", [self class]); // MJStudent
  • 消息接受者:MJStudent的实例对象
  • 最终调用的方法:基类NSObject-(Class)class方法
2021-05-07 16:49:58.626838+0800 Interview05-super[4726:201151] [self class] = MJStudent
NSLog(@"[self superclass] = %@", [self superclass]); // MJPerson
  • 消息接受者:仍然是MJStudent的实例对象
  • 最终调用的方法:基类NSObject-(Class)superclass方法
 NSLog(@"[super class] = %@", [super class]); // MJStudent
  • 消息接受者:MJStudent的实例对象
  • 最终调用的方法:基类NSObject-(Class)class方法
NSLog(@"[super superclass] = %@", [super superclass]); // MJPerson
  • 消息接受者:仍然是MJStudent的实例对象
  • 最终调用的方法:基类NSObject-(Class)superclass方法

我们再回头看看[super class],[super superclass]:

  • [super class]:方法的接受者仍然是self,class()方法内部获取到self的类对象,所以还是Student.
  • [super superclass]:方法的接受者仍然是self,superclass()方法内部会现获取self的类对象Student,在获取Student的父类Person.
特别备注

本系列文章总结自MJ老师在腾讯课堂iOS底层原理班(下)/OC对象/关联对象/多线程/内存管理/性能优化,相关图片素材均取自课程中的课件。如有侵权,请联系我删除,谢谢!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念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

推荐阅读更多精彩内容