一个NSObject对象,转成c++以后里面就是一个结构体,里面就一个isa的指针。
struct NSObject_IMP{
Class isa;
}
所以一个NSObject对象占用的内存也就是成员变量isa所占用的内存,8个字节。但是系统会分配16个字节给它。
获取类的实例对象的size方法
#import <objc/message.h>
NSLog(@"%zd",class_getInstanceSize([NSObject class]));
获取系统给一个对象分配的内存空间
#import <malloc/malloc.h>
NSLog(@"%zd",malloc_size((__bridge const void *)obj));
eg
@interface Person : NSObject
{
@public
int _age; //4
int _height; //4
float _height2; //4
}
@property(nonatomic, copy) NSString *age2; //8
@end
@implementation Person
@end
一个Person对象占用多少内存
Person *p = [[Person alloc] init];
p->_age = 1;
p->_height = 1;
p->_height2 = 1;
[p setAge2:@"2"];
NSLog(@"%zd",class_getInstanceSize([Person class]));
NSLog(@"%zd",malloc_size((__bridge const void *)p));
isa:8
_age:4
_height:4
_height2:4
age2:8
class_getInstanceSize:8(isa)+8(_age+_height)+8(_height2)+8(age2) = 32
malloc_size: 32
注意:分配内存空间有内存对其原则
输出:32 32
eg2
@interface Person2 : NSObject
{
@public
int _age; //4
int _height; //4
float _height2; //4
}
@end
@implementation Person2
@end
一个Person2对象占用多少内存
Person2 *p = [[Person2 alloc] init];
p->_age = 1;
p->_height = 1;
p->_height2 = 1;
NSLog(@"%zd",class_getInstanceSize([Person2 class]));
NSLog(@"%zd",malloc_size((__bridge const void *)p));
isa:8
_age:4
_height:4
_height2:4
class_getInstanceSize:8(isa)+8(_age+_height)+8(_height2)= 24
malloc_size: 32
注意:分配内存空间有内存对其原则
输出:24 32
eg3
@interface Person3 : NSObject
{
@public
int _age; //4
int _height; //4
}
@end
@implementation Person3
@end
一个Person3对象占用多少内存
Person3 *p = [[Person3 alloc] init];
p->_age = 1;
p->_height = 1;
NSLog(@"%zd",class_getInstanceSize([Person3 class]));
NSLog(@"%zd",malloc_size((__bridge const void *)p));
isa:8
_age:4
_height:4
_height2:4
class_getInstanceSize:8(isa)+8(_age+_height) = 16
malloc_size: 16
注意:分配内存空间有内存对其原则
输出:16 16
网友评论