IOS底層原理之a(chǎn)lloc和init以及new

一、疑惑點(diǎn)

采用Object-C語言進(jìn)行開發(fā)的時(shí)候,我們都知道可以通過 [XXX alloc]、[[XXX alloc]init]、[XXX new]的形式進(jìn)行對(duì)象實(shí)例的創(chuàng)建,那么我們不禁會(huì)疑惑alloc、init、new它們各自都做了什么呢?同樣的都是進(jìn)行實(shí)例創(chuàng)建,它們之間有什么內(nèi)在的關(guān)聯(lián)呢?它們之間又有著什么樣的區(qū)別呢?帶著這些疑惑我們一起深入底層探究一下。

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

二、底層源碼探究

既然是深入底層那我們肯定需要知道底層代碼是做了什么,很幸運(yùn)的是蘋果開源了這部分的代碼。可以在這里下載到。下載下來的源碼直接編譯是通不過的,需要自己修改下配置

1、alloc探究

進(jìn)入到alloc的源碼里面,我們發(fā)現(xiàn)alloc調(diào)用了_objc_rootAlloc方法,而_objc_rootAlloc調(diào)用了callAlloc方法。

+ (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())) {
        // 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];
}

在callAlloc方法里面吸引我們注意的是if的判斷條件。fastpath(!cls->ISA()->hasCustomAWZ())都做了什么呢?fastpath又是什么呢?

fastpath的定義是這樣的

#define fastpath(x) (__builtin_expect(bool(x), 1))

我們要搞清楚fastpath是什么,就要知道__builtin_expect是什么。萬能的google告訴了我們答案。這個(gè)指令是gcc引入的,作用是允許程序員將最有可能執(zhí)行的分支告訴編譯器。這個(gè)指令的寫法為:__builtin_expect(EXP, N)。意思是:EXP==N的概率很大

!cls->ISA()->hasCustomAWZ()做了什么呢?很明顯是調(diào)用了hasCustomAWZ這樣一個(gè)方法。

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

RW_HAS_DEFAULT_AWZ 這個(gè)是用來標(biāo)示當(dāng)前的class或者是superclass是否有默認(rèn)的alloc/allocWithZone:。值得注意的是,這個(gè)值會(huì)存儲(chǔ)在metaclass 中。

hasDefaultAWZ( )方法是用來判斷當(dāng)前class是否有重寫allocWithZone。如果cls->ISA()->hasCustomAWZ()返回YES,意味著當(dāng)前的class有重寫allocWithZone方法,那么就直接對(duì)class進(jìn)行allocWithZone,申請(qǐng)內(nèi)存空間。

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

allocWithZone內(nèi)部調(diào)用了_objc_rootAllocWithZone方法,接下來我們分析下_objc_rootAllocWithZone方法。

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);//創(chuàng)建對(duì)象
#else
    if (!zone) {
        obj = class_createInstance(cls, 0);
    }
    else {
        obj = class_createInstanceFromZone(cls, 0, zone);
    }
#endif

    if (slowpath(!obj)) obj = callBadAllocHandler(cls);
    return obj;
}

我們發(fā)現(xiàn)直接調(diào)用了class_createInstance方法來創(chuàng)建對(duì)象,好像已經(jīng)逐漸接近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());
    // Read class's info bits all at once for performance
    //讀取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;
}

哇瑟,一眼看去就暈了!但是靜下心分析下來我們發(fā)現(xiàn)了些端倪。創(chuàng)建對(duì)象就要為對(duì)象開辟內(nèi)存空間,這里會(huì)不會(huì)就是為對(duì)象開辟了空間呢?發(fā)現(xiàn)方法里面調(diào)用了instanceSize方法,這個(gè)是不是就是開辟內(nèi)存空間的方法呢?

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());
}

// May be unaligned depending on class's ivars.
//讀取當(dāng)前的類的屬性數(shù)據(jù)大小
uint32_t unalignedInstanceSize() {
  assert(isRealized());
  return data()->ro->instanceSize;
}
//進(jìn)行內(nèi)存對(duì)齊
//WORD_MASK == 7
static inline uint32_t word_align(uint32_t x) {
   return (x + WORD_MASK) & ~WORD_MASK;
}

哇瑟,我們的猜測(cè)是對(duì)的,instanceSize方法計(jì)算出了對(duì)象的大小,而且必須是大于或等于16字節(jié),然后調(diào)用calloc函數(shù)為對(duì)象分配內(nèi)存空間了。
有必要說明的一點(diǎn)是,對(duì)齊算法使用很巧妙,關(guān)于內(nèi)存對(duì)齊在上一篇文章中我有講解。
由此我們總結(jié)一點(diǎn)alloc創(chuàng)建了一個(gè)對(duì)象并且為其分配了不少于16字節(jié)的內(nèi)存。

但是僅僅是申請(qǐng)了一塊內(nèi)存空間嗎?我們還注意到initInstanceIsa方法,那么這個(gè)方法是干什么的呢?其實(shí)這個(gè)方法就是初始化isa指針,關(guān)于isa在這里不做描述,在后續(xù)的文章中會(huì)專門講解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的情況,有去判斷當(dāng)前的class是否支持快速alloc。如果可以,直接調(diào)用calloc函數(shù),并且申請(qǐng)1塊bits.fastInstanceSize()大小的內(nèi)存空間,然后初始化isa指針,否則直接調(diào)用class_createInstance方法,這樣就走到了我們上面分析流程了。

總結(jié)上面分析流程,我們得出了一個(gè)結(jié)論

alloc為我們創(chuàng)建了一個(gè)對(duì)象并且申請(qǐng)了一塊不少于16字節(jié)的內(nèi)存空間。

alloc流程圖

既然alloc為我們創(chuàng)建了對(duì)象,那還要init干嘛呢?init有做了什么呢?

2、init探究

我們進(jìn)入到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啥都沒做,只是把當(dāng)前的對(duì)象返回了。既然啥都沒做那我們還需要調(diào)用init嗎?答案是肯定的,其實(shí)init就是一個(gè)工廠范式,方便開發(fā)者自行重寫定義。

我們?cè)趤砜纯磏ew方法做了啥。

3、new探究

進(jìn)入到new的底層代碼

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

發(fā)現(xiàn)new調(diào)用的是callAlloc方法和init,那么可以理解為new實(shí)際上就是alloc+init的綜合體。

總結(jié)

  1. alloc創(chuàng)建了對(duì)象并且申請(qǐng)了一塊不少于16字節(jié)的內(nèi)存控件。
  2. init其實(shí)什么也沒做,返回了當(dāng)前的對(duì)象。其作用在于提供一個(gè)范式,方便開發(fā)者自定義。
  3. new其實(shí)是alloc+init的一個(gè)綜合體。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容