OC Super的理解

//我们来看下以下代码打印的结果是什么?

@interface XZPerson : NSObject                      
- (void)run;

@end
@implementation XZPerson

- (void)run{
    NSLog(@"%s",__func__);
}
@end

==============================================================================
@implementation XZStudent
- (void)run{
    [super run];
//转化成 c++代码
// // ((void (*)(__rw_objc_super *, SEL))objc_msgSendSuper)({(id)self, (id)class_getSuperclass(objc_getClass("XZStudent"))}, sel_registerName("run"));
    
//    struct __rw_objc_super  arg = {self,
//        class_getSuperclass(objc_getClass("XZStudent")};
//                            
//    objc_msgSendSuper(
//        arg
//        @selector(run)
//    );
     NSLog(@"XZStudent--%s",__func__);

}
- (instancetype)init{
    if (self == [super init]) {
        NSLog(@"[self class]--%@",[self class]);//XZStudent
        NSLog(@"[self superclass]--%@",[self superclass]);//XZPerson
        NSLog(@"++++++++++++++++");
        NSLog(@"[super class]--%@",[super class]);//XZStudent
        NSLog(@"[super superclass]--%@",[super superclass]);//XZPerson
    }
    return self;
}
@end 
==============================================================================

super调用,底层会转换为objc_msgSendSuper2函数的调用,接收2个参数 struct objc_super2 ,SEL;

struct objc_super2{

       Id receiver;//消息接收者

     Class  super_class;//消息接收者的父类;

};

我们都知道方法调用是从当前类查找方法,然后在通过isa 找到superclass,通过superclass 调用父类的方法。

但是super 方法调用时直接从父类的方法列表中查找,然后找到父类的方法。进行调用。

通过以下方法可以窥探他的实现;汇编语言

猜你喜欢

转载自blog.csdn.net/qq_33726122/article/details/84561412