0%

Class的结构分析

本文使用的objc源码版本为objc4-756.2

Class本质上为一个结构体类型:

1
2
typedef struct objc_class *Class;

与该结构体相关的主要定义如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
struct objc_object {
private:
isa_t isa;
//以下省略
}

struct objc_class : objc_object {
// Class ISA;
Class superclass;
cache_t cache; // 方法缓存
class_data_bits_t bits; // 类的具体信息
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; //协议列表
}

struct class_ro_t {
uint32_t flags;
uint32_t instanceStart;
uint32_t instanceSize; //instance对象占用的内存大小
#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;
}