1. 类对象内存布局
| 组成 | 作用 |
|---|
| isa | 指向该类的元类,用于寻找类方法 |
| super_class | 指向父类 |
| name | 类名 |
| version | 类版本,用于向后兼容 |
| info | 描述类的特性 |
| instanceSize | 类实例对象大小 |
| ivars | 指向实例变量列表的指针 |
| methods | 指向方法列表的指针 |
| cache | 方法调用的缓存 |
| protocols | 指向类遵循的协议列表的指针 |
| ivarLayout | 实例变量的内存布局 |
| dispatchTable | 方法分配表 |
| weakIvarLayout | 弱实例变量内存布局 |
| baseProperties | 指向属性列表的指针 | · |
2. 实例对象的内存布局
| 组成 | 作用 |
|---|
| isa指针 | 用于寻找实例方法 |
| 父类成员变量 | 用于存储数据 |
| 自己成员变量 | 用于存储数据 |
3. 代码示例
@interface Person : NSObject
@property (nonatomic, assign) char char1;
@property (nonatomic, assign) char char2;
@property (nonatomic, assign) char char3;
@property (nonatomic, assign) char char4;
@property (nonatomic, assign) char char5;
@property (nonatomic, assign) int int1;
@property (nonatomic, assign) char char6;
@end
@interface Student : Person
@property (nonatomic, assign) int number;
@end
Person *p = [[Person alloc] init]
// 24 = 8(isa) + 8[1(char1) + 1(char2) + 1(char3) + 1(char4)+ 1(char5) + 3(补全)] + 8[4(int1) + 1(char6) + 3(补全)] = 3*8
NSLog(@"Person:%zd", class_getInstanceSize([Person class]))
// 32 = 2*16 (离24最近,且大于24的16的倍数)
NSLog(@"p:%zd", malloc_size((__bridge const void *)p))
Student *stu = [[Student alloc] init]
// 24 = 8(isa) + 8[4(number) + 1(char1) + 1(char2) + 1(char3) + 1(char4)] + 8[1(char5) + 4(int1) + 1(char6) + 2(补全8)] = 3*8
NSLog(@"Student:%zd",class_getInstanceSize([Student class]))
// 32 = 2*16 (离24最近,且大于24的16的倍数)
NSLog(@"stu:%zd",malloc_size((__bridge const void *)stu))
