查看源码,代码调用顺序

借用cooci的流程图分析
alloc -> _objec_rootAlloc ->callAlloc 到此我们查看源码可以很清楚的看到, 只需cmd + 右键 (jump to Definition)



到达callAlloc 这里代码不再是一行了,出现了if else 判断 我们先看下callAlloc(Class cls, bool checkNil, bool allocWithZone=fals)这里参数
cls:类信息(如NSString)
checkNil:是否需要检查cls为不为nil
allocWithZone:是否使用NSZone,如果直接调用alloc的话,系统会在默认的NSZone里面分配内存。
看callAlloc 的内部实现
这里代码比较多,我们先看看cls->ISA()->hasCustomAWZ(),源码在这


callAlloc 的实现代码,我们发现,最后会返回一个obj的对象。 obj的对象是通过 id obj = class_createInstance(cls, 0); 创建的
我们继续查看 class_createInstance(cls, 0),


代码可以看出,createInstanc 调用的为_class_createInstanceFromZone,查看这里的实现,我们可以发现,对象的创建主要为 obj = (id)calloc(1, size); 分配内存空间 obj->initInstanceIsa(cls, hasCxxDtor); 初始化isa指针

init 干啥的?
平时我们创建对象是 都会使用alloc init 一同使用,那么init 做了什么呢?查看源码我们发现,init 只是返回self,什么事情都没做, 空说无凭,上图为证


2019年12月18日 可能有些地方描述的不准确,请指教,正在学习阶段,轻喷!