在OC开发中最基本的就是对象的建立,也就是用alloc和init方法来初始化对象,可是在咱们平常开发中这个对象建立的最基本最简单的操做咱们只知道怎么使用,并不知道里面的底层到底作了什么,这就是这篇文章的如下须要介绍的alloc底层原理。算法
为了更好的介绍如下的内容定义了一个TestObject的类sass
@interface TestObject : NSObject
@end
#import "TestObject.h"
@implementation TestObject
+ (void)initialize
{
NSLog(@"%s",__func__);
}
+(instancetype)allocWithZone:(struct _NSzone *)zone{
NSLog(@"%s",__func__);
return [super allocWithZone:zone];
}
@end
复制代码
在介绍以前先来一个简单的例子bash
TestObject *test = [TestObject alloc];
TestObject *test1 = [test init];
TestObject *test2 = [test1 init];
NSLog(@"=========输出结果============");
NSLog(@"%@---%p",test,&test);
NSLog(@"%@---%p",test1,&test1);
NSLog(@"%@---%p",test2,&test2);
=========输出结果============
2020-04-28 09:45:04.657448+0800 AllocDemo[3448:65473] <TestObject: 0x600002dfdf70>---0x7ffee4081188
2020-04-28 09:45:04.657608+0800 AllocDemo[3448:65473] <TestObject: 0x600002dfdf70>---0x7ffee4081180
2020-04-28 09:45:04.657769+0800 AllocDemo[3448:65473] <TestObject: 0x600002dfdf70>---0x7ffee4081178
复制代码
从例子能够看到,这三个是同一个对象,可是指针的地址是不一样的,那么问题来了,为何这三个对象地址是同样的?alloc
和init
底层到底作了什么?app
1.能够在Xcode上的Debug->Debug Workflow->Always show Disassembly,如图:函数
2.配合系统断点的形式来就能够一步一步看到alloc底层的每一步的流程。经过这样的方式能够找到alloc的底层的入口,是objc_alloc
底层方法源码分析
objc_alloc
方法是在
libobjc.A.dylib
的库里面,而且它的下一步是
alloc
方法。
可是苹果官方开源了这部分的源码,能够在苹果源码列表找到objc4
,在里面下载,能够配合这个大佬的配置iOS_objc4-756.2 最新源码编译调试让源码能够在Xcode上运行。接下来,我就是根据objc4-756.2
的源码来进行探索的。布局
经过上面的汇编能够知道objc_alloc
是alloc的底层入口,可是咱们经过源码的配置点击进去的话是会直接跳转到post
+ (id)alloc {
return _objc_rootAlloc(self);
}
复制代码
这是一个类方法,这是为何呢? 由于第一次alloc跑到objc_alloc这种是只走一次,缘由就是sel实现imp函数地址,在macho的符号绑定(绑定symbol)的sel_alloc找到能够找到objc_alloc性能
fixupMessageRef
在正常的状况下不走,只有这个对象须要修复的时候才走,因此正常的状况下这个对象就是已经绑定了,因此在正常状况下打断点是不会跑到这里的。
因此经过源码将断点打在objc_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 (slowpath(checkNil && !cls)) return nil;
#if __OBJC2__
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
// No alloc/allocWithZone implementation. Go straight to the allocator.
// fixme store hasCustomAWZ in the non-meta class and
// add it to canAllocFast's summary if (fastpath(cls->canAllocFast())) { // No ctors, raw isa, etc. Go straight to the metal. bool dtor = cls->hasCxxDtor(); id obj = (id)calloc(1, cls->bits.fastInstanceSize()); if (slowpath(!obj)) return callBadAllocHandler(cls); obj->initInstanceIsa(cls, dtor); return obj; } else { // Has ctor or raw isa or something. Use the slower path. id obj = class_createInstance(cls, 0); if (slowpath(!obj)) return callBadAllocHandler(cls); return obj; } } #endif // No shortcuts available. if (allocWithZone) return [cls allocWithZone:nil]; return [cls alloc]; } 复制代码
第一次进来是从objc_alloc
里面进来的,其中checkNil
为true,allocWithZone
为false,由于第一次进来fastpath(!cls->ISA()->hasCustomAWZ())
中的cls尚未指针isa
,因此为false,直接return [cls alloc]
,其中在调用了[cls alloc]
方法会会触发objc_msgSend
调用initialize
类方法,由于这个方法在第一次初始化该类以前会被调用。
#define fastpath(x) (__builtin_expect(bool(x), 1))
#define slowpath(x) (__builtin_expect(bool(x), 0))
slowpath(bool)与fastpath(bool):经常使用于if-else,能够优化判断的速度。
应用gcc指令__builtin_expect(EXP,N) ,经过此指令优化编译器在编译时的代码布局,减小指令跳转带来的性能消耗。
复制代码
经过第一次的callAlloc
返回,根据断点跳转到了
+ (id)alloc {
return _objc_rootAlloc(self);
}
// 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
方法,可是此时的参数checkNil
为false,allocWithZone
为true。由于以前调用了initialize
类方法,此时的bits是有值了,直接进入到了if(fastpath(!cls->ISA()->hasCustomAWZ()))
里面。
bool hasCustomAWZ() {
return ! bits.hasDefaultAWZ();
}
复制代码
hasCustomAWZ
方法意思就是判断是否实现自定义的allocWithZone方法,若是没有实现就调用系统默认的allocWithZone方法。
由于fastpath(cls->canAllocFast())
根据源码返回的永远都是false
bool canAllocFast() {
assert(!isFuture());
return bits.canAllocFast();
}
#if FAST_ALLOC
·····
#else
····
bool canAllocFast() {
return false;
}
#endif
#define FAST_ALLOC (1UL<<2)
复制代码
因此不会执行if里面的代码块,只会执行else里面的代码块
1.类没有实现allocWithZone方法的时候是须要运行fastpath(!cls->ISA()->hasCustomAWZ())
判断里面的代码,最终是经过class_createInstance
的返回
id obj = class_createInstance(cls, 0);
if (slowpath(!obj)) return callBadAllocHandler(cls);
return obj;
复制代码
id class_createInstance(Class cls, size_t extraBytes)
{
return _class_createInstanceFromZone(cls, extraBytes, nil);
}
复制代码
因此这个的流程是:alloc->_objc_rootAlloc->callAlloc(cls,false,true)->class_createInstance->_class_createInstanceFromZone
2.类实现了allocWithZone方法的时候就不会运行fastpath(!cls->ISA()->hasCustomAWZ())
判断里面的代码,直接跑
if (allocWithZone) return [cls allocWithZone:nil];
复制代码
而且这时候会执行类中实现的allocWithZone
方法
2020-04-28 23:55:18.173680+0800 LGTest[2370:69449] +[TestObject allocWithZone:]
复制代码
经过断点的形式获得的流程是: alloc->_objc_rootAlloc->callAlloc(cls,false,true)->allocWithZone->_objc_rootAllocWithZone->class_createInstance->_class_createInstanceFromZone
最终这两种状况下都会执行到_class_createInstanceFromZone
这个函数里面。
这个方法的源代码
static __attribute__((always_inline))
id
_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
bool cxxConstruct = true,
size_t *outAllocatedSize = nil)
{
if (!cls) return nil;
assert(cls->isRealized());
// Read class's info bits all at once for performance //判断当前class或者superclass是否有.cxx_construct构造方法的实现 bool hasCxxCtor = cls->hasCxxCtor(); //判断当前class或者superclass是否有.cxx——destruct析构方法的实现 bool hasCxxDtor = cls->hasCxxDtor(); bool fast = cls->canAllocNonpointer(); //经过进行内存对齐获得实例大小 size_t size = cls->instanceSize(extraBytes); if (outAllocatedSize) *outAllocatedSize = size; id obj; if (!zone && fast) { obj = (id)calloc(1, size); if (!obj) return nil; //初始化实例的isa指针 obj->initInstanceIsa(cls, hasCxxDtor); } else { if (zone) { obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size); } else { obj = (id)calloc(1, size); } if (!obj) return nil; // Use raw pointer isa on the assumption that they might be // doing something weird with the zone or RR. obj->initIsa(cls); } if (cxxConstruct && hasCxxCtor) { obj = _objc_constructOrFree(obj, cls); } return obj; } 复制代码
下面是对_class_createInstanceFromZone
的分析
1.cls->instanceSize(extraBytes)
是进行内存对齐获得的实例大小,里面的流程分别以下:
size_t instanceSize(size_t extraBytes) {
size_t size = alignedInstanceSize() + extraBytes;
// CF requires all objects be at least 16 bytes.
if (size < 16) size = 16;
return size;
}
uint32_t alignedInstanceSize() {
return word_align(unalignedInstanceSize());
}
uint32_t unalignedInstanceSize() {
assert(isRealized());
return data()->ro->instanceSize;
}
static inline uint32_t word_align(uint32_t x) {
return (x + WORD_MASK) & ~WORD_MASK;
}
#ifdef __LP64__
# define WORD_MASK 7UL
#else
# define WORD_MASK 3UL
#endif
复制代码
一开始进来的时候extraBytes为0的,由于当前的TestObject里面是没有属性的,是否是以为开辟的内存空间是0呢?并非的,由于还有一个isa
@interface NSObject <NSObject> {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-interface-ivars"
Class isa OBJC_ISA_AVAILABILITY;
#pragma clang diagnostic pop
}
复制代码
经过流程能够知道在unalignedInstanceSize
方法中获得编译进去的实例的大小,由于isa
是一个对象指针,因此这个的大小是一个8字节。因此传到word_align
方法里面的x为8。其中WORD_MASK
在64位系统下是7,不然是3,所以,word_align()
方法在64位系统下进行计算是8字节对齐按照里面的算法就是至关于8的倍数。返回到instanceSize()
方法中的size
就是对象须要的空间大小为8,由于里面有小于16的返回16。
2.calloc
函数是初始化所分配的内存空间的。
3.initInstanceIsa
函数是初始化isa
,关联cls
的,这部份内容后续会进行介绍。
1.介绍完alloc
以后,init
方法经过源码
- (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;
}
复制代码
其实就是返回它的自己的。
2.new
的方法经过源码知道是 callAlloc
方法和 init
的方法的结合
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}
复制代码
经过上面的流程获得了最终的alloc
在底层的流程图