OC底層探索-alloc流程

在我們平時寫OC代碼時,alloc、init代碼相信沒一個iOS開發(fā)者都已經(jīng)熟悉的不能再熟悉了,那么你是否知道alloc init做了些什么。

alloc

直接上代碼:

LDQPerson *p1 = [LDQPerson alloc];
LDQPerson *p2 = [p1 init];
LDQPerson *p3 = [p1 init];
LGNSLog(@"%@ - %p - %p",p1,p1,&p1);
LGNSLog(@"%@ - %p - %p",p2,p2,&p2);
LGNSLog(@"%@ - %p - %p",p3,p3,&p3);

運行上面代碼


運行結(jié)果.png

從上面的結(jié)果可以知道p1、p2、p3它們都是指向了同一片內(nèi)存,但是用來接收這片內(nèi)存的指針地址是不同的,由此我們可以知道,p1 =[LDQPerson alloc]在進行alloc操作的是后向系統(tǒng)申請了一片內(nèi)存空間0x600002da8940,而后面的p2、p3在進行init時并沒有對這片內(nèi)存空間進行任何的修改。


alloc.png

alloc在開辟內(nèi)存時作的操作

通過查看蘋果OC源碼 objc4-781,oc源碼編譯方法 編譯
可以發(fā)現(xiàn),在進行alloc操作時執(zhí)行了3個方法

  • _objc_rootAlloc
  • callAlloc
  • _objc_rootAllocWithZone

_objc_rootAlloc

//alloc
+ (id)alloc {
    return _objc_rootAlloc(self);
}
//_objc_rootAlloc
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
//callAlloc
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));
}

通過代碼跟蹤到第3步callAlloc方法時里面有幾個if,這是通過斷點調(diào)試可以知道是執(zhí)行了 _objc_rootAllocWithZone方法。
接下來繼續(xù)跟蹤來到_objc_rootAllocWithZone方法內(nèi):

_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_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
                              int construct_flags = OBJECT_CONSTRUCT_NONE,
                              bool cxxConstruct = true,
                              size_t *outAllocatedSize = nil)
{
    //檢查是否已經(jīng)實現(xiàn)
    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;
    //計算需要開辟的內(nèi)存大小
    size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (zone) {
        obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    } else {
        // 去申請內(nèi)存
        obj = (id)calloc(1, size);
    }
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }

    //將 cls類 與 obj指針(即isa) 關(guān)聯(lián)
    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的執(zhí)行流程如下圖

alloc執(zhí)行流程.png

init和new

init就是返回它本身的操作

- (id)init {
    return _objc_rootInit(self);
}
_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;
}

new通過callAlloc、init創(chuàng)建對象

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

new和alloc分別有什么好處? new:寫法比alloc簡單; alloc:支持自定義構(gòu)造。我們可以在創(chuàng)建某個對象是通過alloc、init方法讓它自帶某些屬性。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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