学习笔记 - Class的结构

2020-04-19  本文已影响0人  zhongli_007

马上又要开始新的一天了:加油!

typedef struct objc_class *Class;
再去看 objc_class 的实现
struct objc_class {
    Class _Nonnull isa  OBJC_ISA_AVAILABILITY;

#if !__OBJC2__
    Class _Nullable super_class                              OBJC2_UNAVAILABLE;
    const char * _Nonnull name                               OBJC2_UNAVAILABLE;
    long version                                             OBJC2_UNAVAILABLE;
    long info                                                OBJC2_UNAVAILABLE;
    long instance_size                                       OBJC2_UNAVAILABLE;
    struct objc_ivar_list * _Nullable ivars                  OBJC2_UNAVAILABLE;
    struct objc_method_list * _Nullable * _Nullable methodLists                    OBJC2_UNAVAILABLE;
    struct objc_cache * _Nonnull cache                       OBJC2_UNAVAILABLE;
    struct objc_protocol_list * _Nullable protocols          OBJC2_UNAVAILABLE;
#endif

} OBJC2_UNAVAILABLE;

注意到:OBJC2_UNAVAILABLE 。意味着在objc2.0中这个结构体已经被废弃了。因此我们只能去看objc4源码里有没有

struct objc_object {
   private:
   isa_t isa;
    ...   //方法函数
}
struct objc_class : objc_object {
    // Class ISA;
    Class superclass;
    cache_t cache;             // formerly cache pointer and vtable
    class_data_bits_t bits;    // class_rw_t * plus custom rr/alloc flags
    class_rw_t *data() { 
        return bits.data();
    }
    ...  //方法函数
}
这两个结构体列出了其所有的成员变量以及获取class_rw_t的方法
C++的结构体类似于OC的类,有继承关系。
因此objc_class的结构可以写为
struct objc_class  {
    Class isa;
    Class superclass;
    cache_t cache;             // formerly cache pointer and vtable
    class_data_bits_t bits;    // class_rw_t * plus custom rr/alloc flags
    class_rw_t *data() { 
        return bits.data();
    }
    ...  //方法函数
}
struct class_rw_t {
    // Be warned that Symbolication knows the layout of this structure.
    uint32_t flags;
    uint32_t version;
    const class_ro_t *ro;          //存放类的初始信息
    method_array_t methods;       //方法列表
    property_array_t properties;   //属性列表
    protocol_array_t protocols;    //协议列表
    Class firstSubclass;
    Class nextSiblingClass;
    char *demangledName;
#if SUPPORT_INDEXED_ISA
    uint32_t index;
#endif
  ... //方法函数
}
//这里存放的是类编译时候的初始信息
struct class_ro_t {
    uint32_t flags;
    uint32_t instanceStart;
    uint32_t instanceSize;
#ifdef __LP64__
    uint32_t reserved;
#endif
    const uint8_t * ivarLayout;
    const char * name;
    method_list_t * baseMethodList;
    protocol_list_t * baseProtocols;
    const ivar_list_t * ivars;         //成员变量描述信息
    const uint8_t * weakIvarLayout;
    property_list_t *baseProperties;
};

参考一下小码哥的导图



上一篇下一篇

猜你喜欢

热点阅读