小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
每天一个小知识,稳步前进不用愁。 使用clang还原Objective-C代码在底层的实现,来探索对象的本质是什么! 打开main.m函数,写入如下代码:
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface LGPerson : NSObject
@property (nonatomic, strong) NSString *Name;
@end
@implementation LGPerson
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"Hello, World!");
}
return 0;
}
使用clang命令,生成main.cpp文件
clang -rewrite-objc main.m -o main.cpp
通过分析cpp文件,来探索对象的本质 找到LGPerson的定义与实现,可以发现
typedef struct objc_object LGPerson;
struct LGPerson_IMPL {
struct NSObject_IMPL NSObject_IVARS;
NSString *_Name;
};
LGPerson定义为objc_object类型LGPerson_IMPL是LGPerson的底层实现LGPerson_IMPL中嵌套NSObject_IMPL结构体- 结构体嵌套相当于伪继承 找到NSObject的定义与实现,可以发现
typedef struct objc_object NSObject;
struct NSObject_IMPL {
Class isa;
};
NSObject定义为objc_object类型NSObject_IMPL是NSObject的底层实现- 只有一个
Class类型的成员变量isa找到Class的定义与实现,可以发现
typedef struct objc_class *Class;
struct objc_class {
Class _Nonnull isa __attribute__((deprecated));
} __attribute__((unavailable));
Class类型,本质是objc_class结构体指针,占8字节
找到objc_object的实现,可以发现
struct objc_object {
Class _Nonnull isa __attribute__((deprecated));
};
objc_object只有一个Class类型的成员变量isa- 所有对象的底层实现,本质上都来自于
objc_object结构体
结论:
- 对象的本质是结构体
- 类也是对象,本质同样是结构体
- 万物皆对象,万物皆有isa
- isa本质是结构体指针,占8字节
- 所有对象的底层实现,本质上都来自于objc_object结构体