OC底层原理--创建对象(alloc&init&new)都干了啥
alloc源码分析
本次探索主要基于objc4-781源码 进行分析
首先,通过断点调试源码的方式绘制自定义对象执行alloc操作的整体流程如下图所示:
alloc流程图.png
接下来,我们看下每一步具体做了什么
-
第一步: 进入
callAlloc方法,直接执行return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));// Call [cls alloc] or [cls allocWithZone:nil], with appropriate // shortcutting optimizations. static ALWAYS_INLINE id callAlloc(Class cls, bool checkNil, bool allocWithZone=false) { #if __OBJC2__ if (slowpath(checkNil && !cls)) return nil; if (fastpath(!cls->ISA()->hasCustomAWZ())) { return _objc_rootAllocWithZone(cls, nil); } #endif // No shortcuts available. if (allocWithZone) { return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil); } return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc)); }其中关于
slowpath和fastpath这里需要简要说明下,这两个都是objc源码中定义的宏,其定义如下//x很可能为真, fastpath 可以简称为 真值判断 #define fastpath(x) (__builtin_expect(bool(x), 1)) //x很可能为假,slowpath 可以简称为 假值判断 #define slowpath(x) (__builtin_expect(bool(x), 0))
其中的__builtin_expect指令是由gcc引入的,
1、目的:编译器可以对代码进行优化,以减少指令跳转带来的性能下降。即性能优化
2、作用:允许程序员将最有可能执行的分支告诉编译器。
3、指令的写法为:__builtin_expect(EXP, N)。表示 EXP==N 的概率很大。
4、fastpath 定义中 __builtin_expect((x),1) 表示 x 的值为真的可能性更大;即执行 if 里面语句的机会更大
5、slowpath 定义中的 __builtin_expect((x),0) 表示 x 的值为假的可能性更大。即执行 else 里面语句的机会更大
-
第二步: 调用
alloc方法,方法实现如下+ (id)alloc { return _objc_rootAlloc(self); } -
第三步: 调用
_objc_rootAlloc方法,方法实现如下// Base class implementation of +alloc. cls is not nil. // Calls [cls allocWithZone:nil]. id _objc_rootAlloc(Class cls) { return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/); } -
第四步: 调用
callAlloc方法,具体实现第一步已给出,不过这里callAlloc内部走的是fastpath中的return _objc_rootAllocWithZone(cls, nil); -
第五步: 调用
_objc_rootAllocWithZone方法,方法具体实现如下:NEVER_INLINE id _objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused) { // allocWithZone under __OBJC2__ ignores the zone parameter return _class_createInstanceFromZone(cls, 0, nil, OBJECT_CONSTRUCT_CALL_BADALLOC); } -
第六步: 调用
_class_createInstanceFromZone方法,具体实现如下:/*********************************************************************** * class_createInstance * fixme * Locking: none * * Note: this function has been carefully written so that the fastpath * takes no branch. **********************************************************************/ static ALWAYS_INLINE id _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone, int construct_flags = OBJECT_CONSTRUCT_NONE, bool cxxConstruct = true, size_t *outAllocatedSize = nil) { ASSERT(cls->isRealized()); // Read class's info bits all at once for performance bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor(); bool hasCxxDtor = cls->hasCxxDtor(); bool fast = cls->canAllocNonpointer(); size_t size; size = cls->instanceSize(extraBytes); if (outAllocatedSize) *outAllocatedSize = size; id obj; if (zone) { obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size); } else { obj = (id)calloc(1, size); } if (slowpath(!obj)) { if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) { return _objc_callBadAllocHandler(cls); } return nil; } if (!zone && fast) { obj->initInstanceIsa(cls, hasCxxDtor); } else { // Use raw pointer isa on the assumption that they might be // doing something weird with the zone or RR. obj->initIsa(cls); } if (fastpath(!hasCxxCtor)) { return obj; } construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE; return object_cxxConstructFromClass(obj, cls, construct_flags); }在这一步中包含了
alloc的最核心的三个步骤:计算内存大小,申请内存以及将内存地址与对象进行关联-
计算内存大小:
size = cls->instanceSize(extraBytes);size_t instanceSize(size_t extraBytes) const { if (fastpath(cache.hasFastInstanceSize(extraBytes))) { return cache.fastInstanceSize(extraBytes); } size_t size = alignedInstanceSize() + extraBytes; // CF requires all objects be at least 16 bytes. if (size < 16) size = 16; return size; } -
申请内存:
calloc,返回值obj为具体内存地址obj = (id)calloc(1, size); -
将内存地址与对象进行关联
obj->initInstanceIsa(cls, hasCxxDtor);这一步主要是创建 isa 指针,并将 isa 指针指向申请的内存地址,然后与cls(LYPerson)类进行关联
-
至此,alloc的整个流程我们已经基本了解了,接下来我们看下 init 做了哪些操作
init 源码分析
依然是通过断点跳转至源码具体实现,我们发现 init 的操作异常简单,具体如下:
// Replaced by CF (throws an NSException)
+ (id)init {
return (id)self;
}
- (id)init {
return _objc_rootInit(self);
}
id
_objc_rootInit(id obj)
{
// In practice, it will be hard to rely on this function.
// Many classes do not properly chain -init calls.
return obj;
}
通过上面的源码我们可以发现,不管是类方法还是实例方法,init都是直接返回了对象本身,那么苹果这么做用意何在呢?
这里的init主要作用是提供一个构造方法的入口 ,是通过工厂设计(工厂方法模式),这里能使用id强转的原因,主要还是因为 内存字节对齐后,可以使用类型强转为你所需的类型
至此,对于 init 的原理我们也有了了解,那么最后让我们来看一下new具体做了哪些操作
new 源码分析
依然是通过断点跳转至源码具体实现,我们发现 new 的操作异常简单,具体如下:
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}
过源码可以得知,new 函数中直接调用了 callAlloc 函数(即 alloc 中分析的函数),且调用了 init 函数,所以可以得出 new 其实就等价于 [alloc init] 的结论
但是一般开发中并不建议使用 new ,主要是因为有时会重写 init 方法做一些自定义的操作,而用 new 初始化时调用的是 NSObject 的 init 方法.这种时候就可能会出现无法走到自定义 init 的部分
总结
通过源码调试的方式我们已经了解了对象创建过程中 alloc init new 分别做了哪些东西.了解了这些原理之后可以帮助我们后续更好的理解对象.最后稍微总结下关键点:
-
slowpath和fastpath写法主要是为了实现编译器优化 - 对象创建过程的关键三步分别是:计算内存大小,申请内存以及将内存地址与对象进行关联
- 计算内存大小的时候涉及到内存对齐,以16位进行对齐
-
init主要是提供构造函数的入口,不做其他操作 -
new中的init方法是默认调用的,所以实现了initWith**方法的类调用new方法时无法调用自定义的内容