#import <objc/runtime.h>
#import <malloc/malloc.h>
NSObject *fa = [[NSObject alloc] init];
//一个NSObject实例对象(即指针)所占用8个字节
NSLog(@"&&&&%zd",class_getInstanceSize([fa class]));//8
//实例对象(指针)指向的内存大小是16字节 实际分配了16个字节 但是对象只占用了8个字节
NSLog(@"&&&&%zd",malloc_size((__bridge const void *)fa));//16
Father *father = [[Father alloc]init];
father->_number = 4;
father->_age = 5;
NSLog(@"&&&&%zd",class_getInstanceSize([fa class]));//16
NSLog(@"&&&&%zd",malloc_size((__bridge const void *)fa));//16
实例对象占16个字节(isa8个 number4个 age4个)指针指向的内存是16个字节
内存对齐:我们知道OC对象就是C++结构体,而结构体的大小必须是最大成员大小的倍数,当在多了一个height以后,内存不够用了,然后就需要扩展了。一个int型占4个字节
Father *father = [[Father alloc]init];
father->_number = 4;
father->_age = 5;
father->_height = 175;
NSLog(@"&&&&%zd",class_getInstanceSize([fa class]));//24
NSLog(@"&&&&%zd",malloc_size((__bridge const void *)fa));//32
实例对象占24个字节(isa8个 number4个 age4个 _height4个 需要8的倍数开辟)指针指向的内存是32个字节
网友评论