@implementation xxx : NSObject
- (id)init {
self = [super init];
if (self) {
}
return self;
}
复制代码
self是一个隐藏参数变量,指向当前调用方法的对象,还有一个隐藏参数是_cmd,表明当前方法selector。在runtime时会调用objc_msgSend()方法。bash
super并非隐藏参数,只是编译器的指令符号,在runtime时调用objc_msgSendSuper()方法。函数
当使用 super 调用时,运行时会使用 objc_msgSendSuper
函数:ui
id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
复制代码
objc_super的结构体以下:spa
struct objc_super {
id receiver;
Class superClass;
};
复制代码
当编译器遇到 [super xxxx:] 时,开始作下面几个事:指针
1)构建objc_super的结构体,receiver就是子类,和 self 中相同。
superClass就是父类调用 objc_msgSendSuper 的方法,将这个结构体和xxxx的selector传递过去。
2)从objc_super结构体指向的superClass的方法列表开始找 xxxx的selector,
找到后再用objc_super->receiver去调用这个selector。
复制代码
知道self和super的原理就会很容易明白为何[self class]和[super class]输出结果会是同样的。code
[super init]去self的super中调用init, 而后super会调用其父类的init,以此类推,直到找到根类NSObject中的init。 而后根类中的init负责初始化内存区域,添加一些必要的属性,返回内存指针,延着继承链,指针从上到下进行传递,同时在不一样的子类中能够向内存添加必要的属性。 最后当前类中把内存地址赋值给self参数。对象