OC底层原理初探之对象的本质(三)alloc探索下

本文将要探索的内容:

  • 对象的本质是什么?
  • Clang和xcrun的基础定义。
  • 如何将.m文件编译成.cpp文件。
  • .cpp文件源码分析。
  • 结构体和联合体的区别。
  • 如何指定成员变量的位域?
  • nonpointerIsa指针。
  • isa的64个bit位都存了什么?
  • 属性getter和setter是如何读写的。

对象的本质

探索方式:

由于Objective-C语言是C语言和C++的一种超集,那么可以通过轻量编译器Clang来对Objective-C代码进行rewrite,还原Objective-C代码的底层实现来进行探索。Clang可以将.m文件编译成.cpp文件。

Clang和xcrun

Clang:

Clang是一个由Apple主导的,用C++编写的,基于LLVM的,发布于BSD许可证下的CC++Objective-C的轻量级编译器,其目标(之一)就是超越GCC

xcrun

xcrun是一个Xcode的脚本指令集,其在Clang的基础上进行了封装,更加方便使用。

准备阶段:

.m文件编译成.cpp文件

Clang编译:

clang -rewrite-objc main.m -o main.cpp
复制代码

重写带有UIKit库的文件可能出现的问题:

In file included from ViewController.m:9:
./ViewController.h:9:9: fatal error: 'UIKit/UIKit.h' file not found
#import <UIKit/UIKit.h>
        ^~~~~~~~~~~~~~~
1 error generated.
复制代码

解决方法:

clang -rewrite-objc -fobjc-arc -fobjc-runtime=ios-13.0.0 -isysroot /
Applications/Xcode.app/Contents/Developer/Platforms/
iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.0.sdk main.m
复制代码

xcrun编译:

// 模拟器
xcrun -sdk iphonesimulator clang -arch arm64 -rewrite-objc main.m -o main-arm64.cpp

// 真机
xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m -o main- arm64.cpp
复制代码

分析阶段:

main.m文件里声明一个XJPerson的类:

image.png

打开终端,进入main.m所在文件夹,运行上面命令生成main.cpp。打开main.cpp搜索XJPerson

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享