zoukankan      html  css  js  c++  java
  • OC之runtime(super)

    对于下面的代码,打印的结果是啥

    #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

  • 相关阅读:
    IOS开发教程--怎样使用点9图片
    Android studio 自己主动排版
    17 facade
    递归算法时间复杂度分析与改善
    __FUNCTION__, __LINE__ 有助于debug的宏定义
    表名在数据库中的存储大写和小写略解
    七夕节不撸代码你好意思说自己是程序员
    前端开发面试题收集(js部分)
    总体架构
    立即执行的匿名函数
  • 原文地址:https://www.cnblogs.com/muzichenyu/p/14203733.html
Copyright © 2011-2022 走看看