object-c 對象內(nèi)存分配
@interface BusinessCard2 : NSObject
@property (nonatomic) int _age;
@property (nonatomic) Byte _padding; //放在這里會讓對象分配內(nèi)存空間時多分16字節(jié)=》alloc(32字節(jié))
@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));
分析:對象實例初始化后,在內(nèi)存中格局如下:
實例對象預(yù)留 (4字節(jié)) + age(int 4字節(jié)) + byte(1字節(jié),以及系統(tǒng)內(nèi)存對齊要補全的3字節(jié)) + nsstring(*指針4字節(jié)) + 3個byte(3字節(jié)) ==》sum(17字節(jié)),但因為對象分配內(nèi)存按16字節(jié)增加,所以補充成32字節(jié)。
如下用下面方式:
@interface BusinessCard2 : NSObject
@property (nonatomic) int _age;
@property (nonatomic, retain) NSString *_firstName;
@property (nonatomic) Byte _padding; //如放在這里的話,因為內(nèi)存分配對齊的原則,僅分配16字節(jié)=》alloc(16字節(jié))
@property (nonatomic) Byte _b1;
@property (nonatomic) Byte _b2;
@property (nonatomic) Byte _b3;
@end;
@implementation BusinessCard2
- (void)dealloc{
[__firstName release];
}
@end
實例對象預(yù)留 (4字節(jié)) + age(int 4字節(jié)) + nsstring(*指針4字節(jié)) + 4個byte(4字節(jié),因為相聯(lián),所以用4字節(jié)存儲,不再考慮內(nèi)存對齊問題) ==》sum(16字節(jié))。
補充:short分配為2(字節(jié))
因為object-c中使用的都是指針類型實例對象,所以全部為4字節(jié)。但如果像上面例子使用了基本C的類型,就要考慮內(nèi)存對齊的問題了。

浙公網(wǎng)安備 33010602011771號