一、 在开发中我们总会遇到,当涉及到一些底层代码时,往往无法深入了解,比如我们熟悉的alloc方法

这个时候,直接去上苹果的开源网站 https://opensource.apple.com/,跟着我一步步把需要了解的源码下载下来

1.当前最新的源码是11.3,我们点击打开

2.按住cmd + F,搜索objc

3.点击打开,发现Error,可能是官方还没更新,没办法,还是按照前面1、2步,我们打开11.2的

4.成功打开后,可以看到里面的内容

5.返回上一页,我们直接下载下来

6.下载完成,打开工程

7.全局搜索"alloc {" ,好吧,终于出来,现在开始探索alloc究竟做了什么吧

二、开始探索

逐级往下查看
_objc_rootAlloc > callAlloc ,发现callAlloc方法出现分歧

既然知道源码调用的方法,我们创建一个项目和一个类,并对alloc进行调用,然后在此处打上断点,

然后,使用symbolic打断点,将源码里的方法复制粘贴进去

接着,调试模式设置成汇编模式,然后运行项目

结果发现先走了 _objc_rootAllocWithZone ,然后在走 objc_msgSend

继续,回到苹果源码,从_objc_rootAllocWithZone往下走 ,最终来到_class_createInstanceFromZone方法

_class_createInstanceFromZone 做的事情比较多,不是今天的主题
结论:今天的探索可以得出alloc大概流程

网友评论