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.

你可能感兴趣的:(self与super)