OC对象本质

@interface person:NSObject{
    @public
    int _age;
}
@end
@implementation person


@end

@interface student:person{
@public
    int _six;
    
}
@end
@implementation student

有上面两个对象   person继承于NSObject    student 继承于 person   等价于下面的代码

struct NSObject_IMPL {
    Class isa;
};

struct Person_IMPL {
    struct NSObject_IMPL NSObject_IVARS; // 8
    int _age; // 4
}; // 16 内存对齐:结构体的大小必须是最大成员大小的倍数

struct Student_IMPL {
    struct Person_IMPL Person_IVARS; // 16
    int _no; // 4
}; // 16

通过

      NSLog(@"%zd",class_getInstanceSize([student class])  );

        NSLog(@"%zd",malloc_size((__bridge const void *)p));

打印结果是 16  16 

如果给person增加一个成员变量_num  

那么输出结果是    24  32

下面进行解释一下  NSObject类是占用8个字节  对象是占用16字节

那么person继承于它并增加了两个int的成员变量 那么 pseron 类占用就是 8 +4 +4 =16字节  person对象也是16字节

student 继承于person 并增加了一个int 成员变量 那么 student 类就是暂用了  8 +4 +4 + 4 =20  因为 内存对齐:结构体的大小必须是最大成员大小的倍数 所以student 类占用了 24字节  person对象 = 16+4    因为 内存对齐:结构体的大小必须是最大成员大小的倍数 所以student 对象占用了 32字节

猜你喜欢

转载自www.cnblogs.com/ZhangShengjie/p/9330379.html