object-c 对象内存分配

 

@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的类型,就要考虑内存对齐的问题了。

 

 

posted @ 2013-05-29 12:59  代震军  阅读(1694)  评论(0编辑  收藏  举报