一 Student 占用的内存空间
补充:
1 成员变量占用字节的大小:

2 内存对齐的规则:结构体的内存大小必须是最大成员变量的内存的倍数。
一个 Student 类,继承自NSObject,有两个属性,首先要知道,int 类型占用的字节是4个字节
以下打印结果都是16 ,一个int 类型的成员变量占用4个字节,两个占用8个字节,加上父类的isa 指针,一共16个字节
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <malloc/malloc.h>
@interface Student:NSObject
{
@public
int _no;
int _age;
}
@end
@implementation Student
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSObject *obj = [[NSObject alloc]init];
Student *stu = [[Student alloc]init];
NSLog(@"%zu",malloc_size((__bridge const void *)(stu)));
NSLog(@"%zu",class_getInstanceSize([Student class]));
}
return 0;
}


2 思考 ?
以下还是占用 16个字节的内存空间
person 占用16个字节是因为内存对齐
student 占用16个字节是因为确确实实就是16个字节

本文详细解释了Objective-C中一个名为Student的类如何占用内存空间。通过实例展示了一个包含两个int类型成员变量的Student类继承自NSObject时的具体内存占用情况,并讨论了内存对齐规则及其对内存占用的影响。
1039

被折叠的 条评论
为什么被折叠?



