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

  • 相关阅读:
    寻找金秋
    两个周末,两个湖
    桂花林上,再读“六项精进”
    锄奸杜幸,穷寇勿追
    招聘所见思考
    Xufun’s Node.js Primer
    我的软件过程,一年再读
    企业的生命期限,和组织的危机感
    头痛,偷闲,拾黄叶
    喝酒这件事,和等绿灯的习惯
  • 原文地址:https://www.cnblogs.com/muzichenyu/p/14203733.html
Copyright © 2011-2022 走看看