类对象的内存

先来个图,做一下知识准备
在这里插入图片描述
再来一段代码

struct LGStruct1 {
    double a;       // 8    [0 7]
    char b;         // 1    [8]
    int c;          // 4    (9 10 11 [12 13 14 15]
    short d;        // 2    [16 17] 24
}struct1;

struct LGStruct2 {
    double a;       // 8    [0 7]
    int b;          // 4    [8 9 10 11]
    char c;         // 1    [12]
    short d;        // 2    (13 [14 15] 16
}struct2;

// 家庭作业 : 结构体内存对齐
struct LGStruct3 {
    double a; // 8 [0 7]
    int b;    // 4 [8 11]
    char c;   // 1 [12]
    short d;  //2  (13 [14 15])
    int e;    // 4 [16 19]
    struct LGStruct1 str; // (20 21 22 23 [24 47])
}struct3;
struct LGStruct4 {
    struct LGStruct1 str; // 24 [0 23]
    int a;      // 4 [24 27]
    NSString *dd;  //8  (28 29 30 31 [32 39])
    struct LGStruct1 str1; //24 (28 )
    int b;
}struct4;

struct LGStruct5 {
    struct LGStruct1 str;
    int a;
    int b;
    NSString *dd;

    struct LGStruct1 str1;
}struct5;

struct LGStruct6 {
    struct LGStruct1 str;
    NSString *dd;

    struct LGStruct1 str1;
    int a;
    int b;
}struct6;

struct LGStruct7 {
    struct LGStruct1 str;
    struct LGStruct1 str1;
    NSString *dd;
    int a;
    int b;
}struct7;

struct LGStruct8 {
    struct LGStruct1 str;
    int a;
    struct LGStruct1 str1;
    int b;
}struct8;

struct LGStruct9 {
    struct LGStruct1 str;
    int a;
    int b;
    NSString *dd;

    struct LGStruct1 str1;
}struct9;

struct LGStruct10 {
    struct LGStruct1 str;
    struct LGStruct1 str1;
    int a;
    int b;
}struct10;

NSLog(@"%lu-%lu",sizeof(struct1),sizeof(struct2));
NSLog(@"%lu",sizeof(struct3));
 NSLog(@"%lu-%lu-%lu-%lu",sizeof(struct4),sizeof(struct5),sizeof(struct6),sizeof(struct7));
 NSLog(@"%lu-%lu-%lu",sizeof(struct8),sizeof(struct9),sizeof(struct10));

结果:
32-16
56
88-80-80-80
80-80-72

内存对齐有3个规则:
1 :数据成员对齐规则:结构(struct) (或联合(union))的数据成员,第一个数据成员放在offset为0的地方,以后每个数据成员存储的起始位置要从该成员大小或者成员的子成员大小(只要该成员有子成员,比如说是数组,结构体等)的整数倍 开始(比如int为4字节,则要从4的整数倍地址开始存储。min( 当前开始的位置m n) m=9 n = 4

2 :结构体作为成员:如果一个结构里有某些结构体成员,则结构体成员要从其内部最大元素大小的整数倍地址开始存储. (struct a里存有struct b,b里有char,int , double等元素,那b应该从8的整数倍开始存储. )

3 :最后结构体的总大小,也就是sizeof的结果, 必须是其内部最大成员的整数倍,不足的要补全。

类对象本质

此处参考:https://blog.csdn.net/a_horse/article/details/82532304

1查看NSObjct的定义
有一个Class类的isa指针

@interface NSObject {
#pragma clang diagnostic push
#pragma clang diagnostic ignored “-Wobjc-interface-ivars”
Class isa OBJC_ISA_AVAILABILITY;
#pragma clang diagnostic pop
}
2 本质
是一个struct结构体

3 sizeOf运算符获取空间的大小
sizeOf([NSObject class])

该运算符为编译时,就可以获取大小,类似于宏定义

4 runtime函数获取实例空间大小
创建一个实例对象,至少需要多少内存?(8字节对齐)
#import <objc/runtime.h>
class_getInstanceSize([NSObject class]);

5 malloc获取内存空间的大小
创建一个实例对象,实际上分配了多少内存?(16字节对齐)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值