#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <malloc/malloc.h>
@interface Person:NSObject
{
@public
int _age;
}
@end
@implementation Person
@end
@interface Student: Person
{
@public
int _no;
}
@end
@implementation Student
-(instancetype)init
{
if(self = [super init])
{
NSLog(@"custom");
}
return self;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
// NSLog(@"Hello, World!");
Person *person = [[Person alloc] init];
person->_age = 15;
Student *stu = [[Student alloc] init];
stu->_age = 16;
stu->_no = 10001;
NSLog(@"student sizeof%ld",sizeof(stu));
// NSObject 实例对象的实际大小
NSLog(@"student class_getInstanceSize%zd",class_getInstanceSize([Student class]));
// NSObject 分配的内存大小
NSLog(@"student malloc_size%zd",malloc_size((__bridge const void *)stu));
NSLog(@"person sizeof%ld",sizeof(person));
// NSObject 实例对象的实际大小
NSLog(@"person class_getInstanceSize%zd",class_getInstanceSize([Person class]));
// NSObject 分配的内存大小
NSLog(@"person malloc_size%zd",malloc_size((__bridge const void *)person));
}
return 0;
}
这个面试题有三个知识点,1.所有类都只有8个字节,根本原因每个类都有一个指针,指向类信息的真正存储地址,这个指针就是isa指针 2.类的实际内存,这就根据实际的内容来了? 3.类的分配内存,这里涉及到内存对齐,就是类分配内存会是最大成员所内存的倍数,比如成员所占内存是24,但最大内存是16,那么会分配至少 32个字节
|