类的结构分析

2020-09-17  本文已影响0人  _涼城
类分析初探

基于isa结构分析 ,我们可以通过lldb获取对象的内存情况

创建一个Person类对象
Person *person = [[Person alloc] init];
查看类对象的内存信息
元类
查看类对象内存存在个数

代码

void testClassNum(){
    Class class1 = [Person class];
    Class class2 = [Person alloc].class;
    Class class3 = object_getClass([Person alloc]);
    NSLog(@"\nclass1 -%p\nclass2 -%p\nclass3 -%p\n",class1,class2,class3);
}

结果

类对象在内存中仅存在1个

类对象内存存在个数.png
isa 流程图

isa的指向 :

objc_object & objc_class

我们通过isa结构分析 中编译到main.cpp打开,可以找到几乎所有的类的结构体都是objc_object,所以objc_object根对象

objc_object

typedef struct objc_object NSObject;

struct objc_object {
    Class _Nonnull isa  OBJC_ISA_AVAILABILITY;
};
objc_class

同样的,在main.cpp中我们可以找到,这个Classobjc_class重定义的,所以说类的底层是objc_class类型。

struct NSObject_IMPL {
    Class isa;
};

typedef struct objc_class *Class;

objc/objc-runtime-new.h中我们找到objc_class 是继承于objc_object的,所以对象、类和元类都有 isa

struct objc_class : objc_object 
类结构源码

objc/objc-runtime-new.h中查看objc_class的源码,我们通过lldb辅助调试。

结构
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
lldb调试

 我们查看到第一段地址依旧是isa,第二段地址是superclass,通过p/x NSObject.class,可以知道第二段地址的NSObject不是元类。

类的内存查看.png
查看bits的内存
获取bits首地址

要想知道bits的首地址,已知isa为8字节,superclass为8字节,需要先算出cache的内存大小,从首地址进行偏移后获取到bits的首地址。

查看class_rw_t

根据class_data_bits_t开放的data()获取到class_rw_t

class_rw_t *data() const {
        return bits.data();
  }
获取class_rw_t.png
查看properties()
const property_array_t properties() const {
        auto v = get_ro_or_rwe();
        if (v.is<class_rw_ext_t *>()) {
            return v.get<class_rw_ext_t *>()->properties;
        } else {
            return property_array_t{v.get<const class_ro_t *>()->baseProperties};
        }
    }

Person新增一个属性name

@property (nonatomic, copy) NSString *name

通过lldb获取property_array_t内的信息。

property_list.png
查看methods()
 const method_array_t methods() const {
        auto v = get_ro_or_rwe();
        if (v.is<class_rw_ext_t *>()) {
            return v.get<class_rw_ext_t *>()->methods;
        } else {
            return method_array_t{v.get<const class_ro_t *>()->baseMethods()};
        }
    }

Person新增一个实例方法sayHello,一个类方法testClassMethod;

- (void)say;

+ (void)testClassMethod;

通过lldb获取method_array_t内的信息。

先获取methods地址

methods.png

查看methods内容,但是仅找到了实例方法sayHello,未找到类方法testClassMethod

method_array_content.png
上一篇 下一篇

猜你喜欢

热点阅读