self与super

@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.

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容