@interface MyObjectB : MyObjectA
@end
@implementation MyObjectB
- (instancetype)init {
self = [super init];
MyObjectA *objA = [[MyObjectA alloc] init];
NSLog(NSStringFromClass([self class]));
NSLog(NSStringFromClass([super class]));
return self;
}
@end
輸出是什么?
其實可以通過clang來將代碼編譯為c++后,可以看到
static instancetype _I_MyObjectB_init(MyObjectB * self, SEL _cmd) {
self = ((MyObjectB *(*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("MyObjectB"))}, sel_registerName("init"));
MyObjectA *objA = ((MyObjectA *(*)(id, SEL))(void *)objc_msgSend)((id)((MyObjectA *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("MyObjectA"), sel_registerName("alloc")), sel_registerName("init"));
((Class (*)(id, SEL))(void *)objc_msgSend)((id)self, sel_registerName("class"));
((Class (*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("MyObjectB"))}, sel_registerName("class"));
return self;
}
[super class]
轉化成
objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("MyObjectB"))}, sel_registerName("class"))
再參考id objc_msgSendSuper(struct objc_super *super, SEL op, ...);
的說明
Parameters
super
A pointer to an 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.
receiver任然是self,但從superclass的方法列表開始查找方法。所以輸出都為MyObjectB
.