IOS底层原理之alloc、init和new

1、疑惑点

采用Object-C语言进行开发的时候,咱们都知道能够经过 [XXX alloc]、[[XXX alloc]init]、[XXX new]的形式进行对象实例的建立,那么咱们不由会疑惑alloc、init、new它们各自都作了什么呢?一样的都是进行实例建立,它们之间有什么内在的关联呢?它们之间又有着什么样的区别呢?带着这些疑惑咱们一块儿深刻底层探究一下。git

Person *p = [Person alloc];
Person *p1 = [[Person alloc]init];
Person *p2 = [Person new];
NSLog(@"%p,%p,%p",p,p1,p2);
复制代码

2、底层源码探究

既然是深刻底层那咱们确定须要知道底层代码是作了什么,很幸运的是苹果开源了这部分的代码。能够在这里下载到。下载下来的源码直接编译是通不过的,须要本身修改下配置程序员

一、alloc探究

进入到alloc的源码里面,咱们发现alloc调用了_objc_rootAlloc方法,而_objc_rootAlloc调用了callAlloc方法。github

+ (id)alloc {
    return _objc_rootAlloc(self);
}

id _objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}

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

在callAlloc方法里面吸引咱们注意的是if的判断条件。fastpath(!cls->ISA()->hasCustomAWZ())都作了什么呢?fastpath又是什么呢?算法

fastpath的定义是这样的bash

#define fastpath(x) (__builtin_expect(bool(x), 1))
复制代码

咱们要搞清楚fastpath是什么,就要知道__builtin_expect是什么。万能的google告诉了咱们答案。这个指令是gcc引入的,做用是容许程序员将最有可能执行的分支告诉编译器。这个指令的写法为:__builtin_expect(EXP, N)。意思是:EXP==N的几率很大app

!cls->ISA()->hasCustomAWZ()作了什么呢?很明显是调用了hasCustomAWZ这样一个方法。函数

bool hasDefaultAWZ( ) {
    return data()->flags & RW_HAS_DEFAULT_AWZ;
}
#define RW_HAS_DEFAULT_AWZ (1<<16)
复制代码

RW_HAS_DEFAULT_AWZ 这个是用来标示当前的class或者是superclass是否有默认的alloc/allocWithZone:。值得注意的是,这个值会存储在metaclass 中。ui

hasDefaultAWZ( )方法是用来判断当前class是否有重写allocWithZone。若是cls->ISA()->hasCustomAWZ()返回YES,意味着当前的class有重写allocWithZone方法,那么就直接对class进行allocWithZone,申请内存空间。this

if (allocWithZone) return [cls allocWithZone:nil];
+ (id)allocWithZone:(struct _NSZone *)zone {
    return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone);
}
复制代码

allocWithZone内部调用了_objc_rootAllocWithZone方法,接下来咱们分析下_objc_rootAllocWithZone方法。google

id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone)
{
    id obj;

#if __OBJC2__
    // allocWithZone under __OBJC2__ ignores the zone parameter
    (void)zone;
    obj = class_createInstance(cls, 0);//建立对象
#else
    if (!zone) {
        obj = class_createInstance(cls, 0);
    }
    else {
        obj = class_createInstanceFromZone(cls, 0, zone);
    }
#endif

    if (slowpath(!obj)) obj = callBadAllocHandler(cls);
    return obj;
}
复制代码

咱们发现直接调用了class_createInstance方法来建立对象,好像已经逐渐接近alloc的真相了。

id class_createInstance(Class cls, size_t extraBytes)
{
    return _class_createInstanceFromZone(cls, extraBytes, nil);
}

tatic __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());
    //读取class的信息
    bool hasCxxCtor = cls->hasCxxCtor();
    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;
        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;
}
复制代码

哇瑟,一眼看去就晕了!可是静下心分析下来咱们发现了些端倪。建立对象就要为对象开辟内存空间,这里会不会就是为对象开辟了空间呢?发现方法里面调用了instanceSize方法,这个是否是就是开辟内存空间的方法呢?

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;
}
//进行内存对齐
//WORD_MASK == 7
static inline uint32_t word_align(uint32_t x) {
    return (x + WORD_MASK) & ~WORD_MASK;
}
复制代码

哇瑟,咱们的猜想是对的,instanceSize方法计算出了对象的大小,并且必须是大于或等于16字节,而后调用calloc函数为对象分配内存空间了。 有必要说明的一点是,对齐算法使用很巧妙,关于内存对齐在上一篇文章中我有讲解。 由此咱们总结一点alloc建立了一个对象而且为其分配了很多于16字节的内存。

可是仅仅是申请了一块内存空间吗?咱们还注意到initInstanceIsa方法,那么这个方法是干什么的呢?其实这个方法就是初始化isa指针,关于isa在这里不作描述,在后续的文章中会专门讲解isa。

刚才咱们分析了hasDefaultAWZ( )方法返回Yes的状况,那若是hasDefaultAWZ( )方法返回NO呢。

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

这一段是hasDefaultAWZ( )返回NO的状况,有去判断当前的class是否支持快速alloc。若是能够,直接调用calloc函数,而且申请1块bits.fastInstanceSize()大小的内存空间,而后初始化isa指针,不然直接调用class_createInstance方法,这样就走到了咱们上面分析流程了。

总结上面分析流程,咱们得出了一个结论

alloc为咱们建立了一个对象而且申请了一块很多于16字节的内存空间。

alloc流程图

既然alloc为咱们建立了对象,那还要init干吗呢?init有作了什么呢?

二、init探究

咱们进入到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;
}

复制代码

额的天呐,init啥都没作,只是把当前的对象返回了。既然啥都没作那咱们还须要调用init吗?答案是确定的,其实init就是一个工厂范式,方便开发者自行重写定义。

咱们在来看看new方法作了啥。

三、new探究

进入到new的底层代码

+ (id)new {
    return [callAlloc(self, false/*checkNil*/) init];
}
复制代码

发现new调用的是callAlloc方法和init,那么能够理解为new实际上就是alloc+init的综合体。

总结

  1. alloc建立了对象而且申请了一块很多于16字节的内存空间。
  2. init其实什么也没作,返回了当前的对象。其做用在于提供一个范式,方便开发者自定义。
  3. new实际上是alloc+init的一个综合体。
相关文章
相关标签/搜索