ObjC Runtime简析 -- super和superclass

栏目: Objective-C · 发布时间: 7年前

内容简介:这一个经典的面试题,Student是Person的一个子类,在子类Student的init方法中调用4个方法并打印结果。objc_msgSend(self, sel_registerName("class")) objc_msgSend(self, sel_registerName("superclass")) objc_msgSendSuper({self, class_getSuperclass(objc_getClass("Student"))}, sel_registerName("class"))

这一个经典的面试题,Student是Person的一个子类,在子类Student的init方法中调用4个方法并打印结果。

ObjC Runtime简析 -- super和superclass

objc_msgSend(self, sel_registerName("class")) objc_msgSend(self, sel_registerName("superclass")) objc_msgSendSuper({self, class_getSuperclass(objc_getClass("Student"))}, sel_registerName("class")) objc_msgSendSuper({(id)self, (id)class_getSuperclass(objc_getClass("Student"))}, sel_registerName("superclass"))

将这个 Student.m 转换为cpp文件查看其底层的方法调用的到如下调用:

[self class]: objc_msgSend(self, sel_registerName("class"))
[self superclass]: objc_msgSend(self, sel_registerName("superclass"))
[super class]: objc_msgSendSuper({self, class_getSuperclass(objc_getClass("Student"))}, sel_registerName("class"))
[super superclass]: objc_msgSendSuper({self, class_getSuperclass(objc_getClass("Student"))}, sel_registerName("superclass"))
复制代码

我们看到当对self进行消息发送的时候底层是调用了runtime的 objc_msgSend 方法,而对super进行消息发送的时候底层是调用了 objc_getSuperClass 。

objc_msgSend 方法我们都熟悉了,将会从self开始查找 class 方法和 superclass 方法的实现,调用打印Student和Person。

而对super发送消息,底层将会调用 objc_msgSendSuper 函数,这个函数有两个参数,第一个是一个结构,第二个是方法选择器。结构体有两个成员:

ObjC Runtime简析 -- super和superclass

第一个是消息接受者,第二个参数我们通过注释可以看出,表示函数从哪里开始查找法方法。而这里传递的是 class_getSuperclass(objc_getClass("Student")) 表示Student的父类,也就是Person类开始查找方法。查找的方法是 class 和 superclass ,而这两个方法存在于 NSObject 中,查找到了之后依然使用 objc_msgSendSuper 第一个参数结构体的第一个成员接收消息。消息接受者是 self ,所以依然调用 self 的 class 方法和 superclass 。

所以最终 [super class] 和 [super superclass] 打印的依然是Student和Person。

总结

对super发消息底层调用的是 objc_msgSendSuper 方法,它有两个参数,第一个是一个结构,第二个是方法选择器。本质上所做的操作是从当前类的父类开始查找方法,而消息的接受者依然是self,也就是当前类,所以最后还是 [self xxxx] 。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

复杂性思考

复杂性思考

Allen B. Downey / 张龙 / 机械工业出版社 / 2013-5 / 49.00元

本书的灵感来源于无聊与迷恋的感觉:对常规的数据结构与算法介绍的无聊,对复杂系统的迷恋。数据结构的问题在于教师在教授这门课程的时候通常不会调动起学生的积极性;复杂性科学的问题在于学校通常不会教授这门课程。 2005年,我在欧林学院讲授了一门新课程,学生要阅读关于复杂性的主题,使用Python进行实验,并学习算法与数据结构。当我在2008年再次讲授这门课程时,我写了本书的初稿。 在2011......一起来看看 《复杂性思考》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具