博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
object-c 对象内存分配
阅读量:4663 次
发布时间:2019-06-09

本文共 1235 字,大约阅读时间需要 4 分钟。

 

@interface BusinessCard2 : NSObject

@property (nonatomic) int _age;
@property (nonatomic) Byte _padding; //放在这里会让对象分配内存空间时多分16字节=》alloc(32字节)
@property (nonatomic, retain) NSString *_firstName;
@property (nonatomic) Byte _b1;
@end;
@implementation BusinessCard2
- (void)dealloc{
    [__firstName release];
}
@end

 

测试:

    BusinessCard2 *card2 = [[BusinessCard2 alloc] init];

    card2._firstName = @"adfadsfds";
    NSLog(@"===BusinessCard2 size==%d", malloc_size(card2));

 

分析:对象实例初始化后,在内存中格局如下:

实例对象预留 (4字节)   +  age(int 4字节) + byte(1字节,以及系统内存对齐要补全的3字节) + nsstring(*指针4字节) + 3个byte(3字节)     ==》sum(17字节),但因为对象分配内存按16字节增加,所以补充成32字节。

 

如下用下面方式:

@interface BusinessCard2 : NSObject

@property (nonatomic) int _age;
@property (nonatomic, retain) NSString *_firstName;
@property (nonatomic) Byte _padding; //如放在这里的话,因为内存分配对齐的原则,仅分配16字节=》alloc(16字节)
@property (nonatomic) Byte _b1;
@property (nonatomic) Byte _b2;
@property (nonatomic) Byte _b3;
@end;
@implementation BusinessCard2
- (void)dealloc{
    [__firstName release];
}
@end

 

实例对象预留 (4字节)   +  age(int 4字节) + nsstring(*指针4字节) + 4个byte(4字节,因为相联,所以用4字节存储,不再考虑内存对齐问题)     ==》sum(16字节)。

补充:short分配为2(字节)

因为object-c中使用的都是指针类型实例对象,所以全部为4字节。但如果像上面例子使用了基本C的类型,就要考虑内存对齐的问题了。

 

 

转载于:https://www.cnblogs.com/daizhj/articles/3105761.html

你可能感兴趣的文章
熟悉常用的HDFS操作
查看>>
面向对象和面向过程的比较
查看>>
数据结构 树的建立与遍历
查看>>
[置顶] java swing的树操作(增删改)
查看>>
jetty对sessionId的处理分析
查看>>
代理的四种实现方式
查看>>
12-29 注册审核
查看>>
计算一个算数表达式的值
查看>>
hdu squarefree number
查看>>
atc-前端模板预编译器
查看>>
SDF(Signed-distance-field: 有向距离场)(7): 距离场函数-基于CUBE计算方式产生的若干变体A...
查看>>
poj 3468 A Simple Problem with Integers 线段树区间加,区间查询和
查看>>
Codeforces Round #194 (Div. 1) A. Secrets 数学
查看>>
看不懂 ASP.NET 相册上传代码
查看>>
redis+mysql
查看>>
IIS中找不到dll文件的依赖项问题
查看>>
Loadrunner的stock和web协议对应的事务检查点
查看>>
mvc扩展HtmlHelper功能
查看>>
codeforces #541 D. Gourmet choice(拓扑+并查集)
查看>>
ocilib linux编译安装
查看>>