iOS的OC对象建立的alloc原理

前言

在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
复制代码

从例子能够看到,这三个是同一个对象,可是指针的地址是不一样的,那么问题来了,为何这三个对象地址是同样的?allocinit底层到底作了什么?app

1.经过汇编来对alloc的探索

1.能够在Xcode上的Debug->Debug Workflow->Always show Disassembly,如图:函数

Xcode开启汇编
固然,这种方式是对整个项目对全局操做的,那么就在须要用到的时候,先打断点,而后再开启。

2.配合系统断点的形式来就能够一步一步看到alloc底层的每一步的流程。经过这样的方式能够找到alloc的底层的入口,是objc_alloc底层方法源码分析

alloc的入口
经过系统的断点,知道 objc_alloc方法是在 libobjc.A.dylib的库里面,而且它的下一步是 alloc方法。

objc_alloc的底层方法
虽然这种方式能够知道底层的流程走向。可是具体的各个函数的实现是不清楚的,而且这种方式也比较麻烦不直观。

2.源码分析alloc底层

可是苹果官方开源了这部分的源码,能够在苹果源码列表找到objc4,在里面下载,能够配合这个大佬的配置iOS_objc4-756.2 最新源码编译调试让源码能够在Xcode上运行。接下来,我就是根据objc4-756.2的源码来进行探索的。布局

2.1 alloc的入口objc_alloc

经过上面的汇编能够知道objc_alloc是alloc的底层入口,可是咱们经过源码的配置点击进去的话是会直接跳转到post

+ (id)alloc {
    return _objc_rootAlloc(self);
}
复制代码

这是一个类方法,这是为何呢? 由于第一次alloc跑到objc_alloc这种是只走一次,缘由就是sel实现imp函数地址,在macho的符号绑定(绑定symbol)的sel_alloc找到能够找到objc_alloc性能

经过源码能够知道其中方法 fixupMessageRef在正常的状况下不走,只有这个对象须要修复的时候才走,因此正常的状况下这个对象就是已经绑定了,因此在正常状况下打断点是不会跑到这里的。

因此经过源码将断点打在objc_alloc方法上,进行下一步优化

2.2 callAlloc

// 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类方法,由于这个方法在第一次初始化该类以前会被调用。

因此第一次的流程是最外面的 alloc-->objec_alloc-->callAlloc(Class cls, true, false)

#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) ,经过此指令优化编译器在编译时的代码布局,减小指令跳转带来的性能消耗。
复制代码

2.3 alloc的第二次流程

经过第一次的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()))里面。

2.3.1 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里面的代码块

2.3.2 类中实现allocWithZone类方法对流程的影响

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这个函数里面。

2.3.4 _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的,这部份内容后续会进行介绍。

2.4 init和new

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];
}
复制代码

3.最后

经过上面的流程获得了最终的alloc在底层的流程图

alloc的流程图
相关文章
相关标签/搜索