oc 继承关系中,实例对象内存字节对齐

204 阅读1分钟

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最近,且大于2416的倍数)
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最近,且大于2416的倍数)
NSLog(@"stu:%zd",malloc_size((__bridge  const void *)stu));

image.png