对于下面的代码,打印的结果是啥
#import "LBStudent.h" @implementation LBStudent - (instancetype)init { self = [super init]; if (self) { NSLog(@"[self class] = %@", [self class]); NSLog(@"[super class] = %@", [super class]); NSLog(@"[self superclass] = %@", [self superclass]); NSLog(@"[super superclass] = %@", [super superclass]); } return self; } @end
调用之后打印结果如下:
[self class] = LBStudent [super class] = LBStudent [self superclass] = LBPerson [super superclass] = LBPerson
可以看到self和super调用class方法,打印的结果是一样的
将上面OC代码转成C++代码之后得到如下代码:
static instancetype _I_LBStudent_init(LBStudent * self, SEL _cmd) { self = ((LBStudent *(*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("LBStudent"))}, sel_registerName("init")); if (self) { NSLog((NSString *)&__NSConstantStringImpl__var_folders_3q_7klqgj0j63z08zcx0skwjm500000gn_T_LBStudent_ad579e_mi_0, ((Class (*)(id, SEL))(void *)objc_msgSend)((id)self, sel_registerName("class"))); NSLog((NSString *)&__NSConstantStringImpl__var_folders_3q_7klqgj0j63z08zcx0skwjm500000gn_T_LBStudent_ad579e_mi_1, ((Class (*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("LBStudent"))}, sel_registerName("class"))); NSLog((NSString *)&__NSConstantStringImpl__var_folders_3q_7klqgj0j63z08zcx0skwjm500000gn_T_LBStudent_ad579e_mi_2, ((Class (*)(id, SEL))(void *)objc_msgSend)((id)self, sel_registerName("superclass"))); NSLog((NSString *)&__NSConstantStringImpl__var_folders_3q_7klqgj0j63z08zcx0skwjm500000gn_T_LBStudent_ad579e_mi_3, ((Class (*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("LBStudent"))}, sel_registerName("superclass"))); } return self; }
从上面代码可以看出,super其实调用的是self的objc_msgSendSuper,而class方法是类继承于NSObject时拥有的,class的方法伪代码实现大概如下:
- (Class)class { return objc_getClass(self); }
class是返回消息接收者的类,super只是代表从父类中开始查找,消息接受者仍然是self