Objective-C 的 self 和 super 详解 (用简单程序说明问题)
在 Objective-C 中的类实现中经常看到这两个关键字 ”self” 和 ”super”,以以前 oop 语言的经验,拿 c++ 为例,self 相当于 this,super 相当于调用父类的方法,这么看起来是很容易理解的。以下面的代码为例:
复制代码 上面有简单的两个类,在子类PersonMe中调用了自己类中的setAge和父类中的setName,这些代码看起来很好理解,没什么问题。
复制代码 这样在调用时,会打出来这两个的class,先猜下吧,会打印出什么?按照以前oop语言的经验,这里应该会输出:
但是编译运行后,可以发现结果是:
self 的 class 和预想的一样,怎么 super 的 class 也是 PersonMe? 真相 self 是类的隐藏的参数,指向当前当前调用方法的类,另一个隐藏参数是 _cmd,代表当前类方法的 selector。这里只关注这个 self。super 是个啥?super 并不是隐藏的参数,它只是一个“编译器指示符”,它和 self 指向的是相同的消息接收者,拿上面的代码为例,不论是用 [self setName] 还是 [super setName],接收“setName”这个消息的接收者都是 PersonMe* 当使用 self 调用方法时,会从当前类的方法列表中开始找,如果没有,就从父类中再找;而当使用 super 时,则从父类的方法列表中开始找。然后调用父类的这个方法 One more step 这种机制到底底层是如何实现的?其实当调用类方法的时候,编译器会将方法调用转成一个 C 函数方法调用,Apple 的 objcRuntimeRef 上说:
可以看到会转成调用上面 4 个方法中的一个,由于 _stret 系列的和没有 _stret 的那两个类似,先只关注 objc_msgSend 和 objc_msgSendSuper 两个方法。当使用 [self setName] 调用时,会使用 objc_msgSend 的函数,先看下 objc_msgSend 的函数定义:
复制代码 第一个参数是消息接收者,第二个参数是调用的具体类方法的 selector,后面是 selector 方法的可变参数。我们先不管这个可变参数,以 [self setName:] 为例,编译器会替换成调用 objc_msgSend 的函数调用,其中 theReceiver 是 self,theSelector 是 @selector(setName),这个 selector 是从当前 self 的 class 的方法列表开始找的 setName,当找到后把对应的 selector 传递过去。 而当使用 [super setName] 调用时,会使用 objc_msgSendSuper 函数,看下 objc_msgSendSuper 的函数定义:
复制代码 第一个参数是个objc_super的结构体,第二个参数还是类似上面的类方法的selector,先看下objc_super这个结构体是什么东西:
复制代码 可以看到这个结构体包含了两个成员,一个是 receiver,这个类似上面 objc_msgSend 的第一个参数 receiver,第二个成员是记录写 super 这个类的父类是什么,拿上面的代码为例,当编译器遇到 PersonMe 里 setName:andAge 方法里的 [super setName:] 时,开始做这几个事:
里面的调用机制大体就是这样了,以上面的分析,回过头来看开始的代码,当输出 [self class] 和 [super class] 时,是个怎样的过程。 当使用 [self class] 时,这时的 self 是 PersonMe,在使用 objc_msgSend 时,第一个参数是 receiver 也就是 self,也是 PersonMe* me 这个实例。第二个参数,要先找到 class 这个方法的 selector,先从 PersonMe 这个类开始找,没有,然后到 PersonMe 的父类 Person 中去找,也没有,再去 Person 的父类 NSObject 去找,一层一层向上找之后,在 NSObject 的类中发现这个 当使用 [super class] 时,这时要转换成 objc_msgSendSuper 的方法。先构造 objc_super 的结构体吧,第一个成员变量就是 self,第二个成员变量是 Person,然后要找 class 这个 selector,先去 superClass 也就是 Person 中去找,没有,然后去 Person 的父类中去找,结果还是在 NSObject 中找到了。然后内部使用函数 objc_msgSend(objc_super->receiver, @selector(class)) 去调用,此时已经和我们用 |
最新文章
- MSMQ学习
- ASP.NET MVC 5 - 控制器
- nodejs解决找不到express命令的问题
- OSG入门即osgEarth建立一个地球的详细步骤
- 为什么不能把委托(delegate)放在一个接口(interface)当中?
- linux开发神器--Tmux
- JMeter学习参数化User Defined Variables与User Parameters
- 树莓派连接wifi
- Nginx反向代理讲解和配置
- js给定时器调用传递参数
- oracle插入主键数据、sequence和触发器
- iBatis调用存储过程以及MySQL创建存储过程
- 异步socket大并发实现
- 用css样式围剿等高列问题(转载)
- MySQL 5.7贴心参数之 log_timestamps
- UWP Composition API - RadialMenu
- A very hard Aoshu problem(dfs或者数位)
- Java基础学习笔记十九 IO
- Rails中rspec测试xxx_path调用失败的解决
- Fourier Transform Complex Conjugate Discussion
热门文章
- How to Have a Healthy Relationship --shanbei 为单身节写
- 【网络】<;网络是怎样连接的>;笔记
- 关于bind named.conf.options
- 前端之css样式01
- VC++6.0/MFC中如何限制Edit控件输入 例子,只能输入0和1
- 【学习】JennyHui学自动化测试
- HDU - 5297:Y sequence (迭代&;容斥)
- ZOJ-Big string(服气思维)
- 【spring源码学习】spring的远程调用实现源码分析
- C++笔记之CopyFile和MoveFile的使用