0%

继承关系的内存布局

定义如下两个类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

@interface Person : NSObject
@property (nonatomic,assign) int age;
@end

@implementation Person
@end

@interface Student : Person
@property (nonatomic,assign) int no;
@end

@implementation Student
@end

将其转换为C++代码可见其底层实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct NSObject_IMPL {
Class isa;
};

struct Person_IMPL {
struct NSObject_IMPL NSObject_IVARS;
int _age;
};

struct Student_IMPL {
struct Person_IMPL Person_IVARS;
int _no;
};

可见子类实例对象的结构体中会包含父类的结构体,且父类的结构体存储在最前。