NSObject底层
看下NSObject中的定义:
1 | @interface NSObject <NSObject> |
其实NSObject就是一个Class对象,不过是对变量isa封装了一系列的操作而已,那么Class又是什么类型呢?在objc-runtime-new.h可以找到其定义,是指向结构体objc_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
49
50
51
52struct objc_class {
Class _Nonnull isa OBJC_ISA_AVAILABILITY; //isa指针
} OBJC2_UNAVAILABLE;
struct objc_class : objc_object {
// Class ISA;
Class superclass; // superclass指针
cache_t cache; // 方法缓存
class_data_bits_t bits; // 数据
// 通过(bits & FAST_DATA_MASK)获取 class_rw_t 数据
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;
method_list_t *baseMethods() const {
return baseMethodList;
}
};
再来看一张图
实例、类、元类 存储信息
instance对象在内存中存储的信息包括
- isa 指针
- 其他成员变量
class类对象在内存中存储的信息主要包括
- isa 指针
- superclass 指针
- 类的属性信息(@property)
- 类的对象方向方法信息(instance method)
- 类的协议信息(protocol)
- 类的成员变量信息(ivar)
- …
meta-class元类对象和class对象的内存结构是一样的,但是用途不一样,在内存中存储的信息主要包括
- isa 指针
- superclass 指针
- 类的类方向方法信息(class method)
- ….
isa指针
在arm64架构之前,isa就是一个普通的指针,存储着Class、Meta-Class对象的内存地址
从arm64架构开始,对isa进行了优化,变成了一个共用体(union)结构,还使用位域来存储更多的信息
1 | union isa_t |