iOS底層原理-001 探索alloc

alloc與init在對(duì)象初始化的作用

先列出一段代碼與輸出結(jié)果

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

輸出結(jié)果

    <LGPerson: 0x600000459a80> - 0x600000459a80 - 0x7ffeea9431c8
    <LGPerson: 0x600000459a80> - 0x600000459a80 - 0x7ffeea9431c0
    <LGPerson: 0x600000459a80> - 0x600000459a80 - 0x7ffeea9431b8

發(fā)現(xiàn)三個(gè)對(duì)象都指向同一塊內(nèi)存空間,初步認(rèn)定init并沒有對(duì)p1做了處理,內(nèi)存空間由alloc申請(qǐng)開辟。
在p1初始化出打斷點(diǎn)句號(hào),進(jìn)入斷點(diǎn)alloc

+ (instancetype)alloc OBJC_SWIFT_UNAVAILABLE("use object initializers instead");

跳到這里就不能更近一步了,顯然這樣不行。

使用匯編

打開匯編

在這里設(shè)置打開匯編,運(yùn)行代碼

    0x10004dc66 <+54>:  movq   0x47d3(%rip), %rax        ; (void *)0x0000000100052538: LGPerson
    0x10004dc6d <+61>:  movq   %rax, %rdi
    0x10004dc70 <+64>:  callq  0x10004e430               ; symbol stub for: objc_alloc

在callq這一行發(fā)現(xiàn)symbol stub for: objc_alloc, 打斷點(diǎn),按住ctl,step into進(jìn)入objc_alloc

設(shè)置符號(hào)斷點(diǎn)

跳轉(zhuǎn)后的代碼是這樣:

001-alloc&init探索`objc_alloc:

使用設(shè)置符號(hào)斷點(diǎn),可以看到所在庫為libobjc.A.dylib ID 6.1


objc_alloc所在庫

開源庫

進(jìn)入蘋果開源庫,下載objc最新版本。

objc開源庫

打開下載好的開源庫,全局搜索alloc方法,結(jié)果如下

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

然后進(jìn)入_objc_rootAlloc方法

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

繼續(xù)進(jìn)入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));
}

會(huì)看到if語句,不確定執(zhí)行哪一個(gè)。然后返回我們的代碼,將每一個(gè)方法都設(shè)置符號(hào)斷點(diǎn)。


符號(hào)斷點(diǎn)

會(huì)發(fā)現(xiàn)最后停止在libobjc.A.dylib`_objc_rootAllocWithZone:

libobjc.A.dylib`_objc_rootAllocWithZone:

繼續(xù)往下 _objc_rootAllocWithZone

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

再往下跳轉(zhuǎn)就進(jìn)入了alloc的核心方法_class_createInstanceFromZone內(nèi)部

_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
                              int construct_flags = OBJECT_CONSTRUCT_NONE,
                              bool cxxConstruct = true,
                              size_t *outAllocatedSize = nil)
{
    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;

    size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (zone) {
        obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    } else {
        obj = (id)calloc(1, size);
    }
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }

    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);
}
1)要開辟多少內(nèi)存

cls->canAllocNonpointer方法

    size_t instanceSize(size_t extraBytes) const {
        if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
            return cache.fastInstanceSize(extraBytes);
        }

        size_t size = alignedInstanceSize() + extraBytes;
        // CF requires all objects be at least 16 bytes.
        if (size < 16) size = 16;
        return size;
    }

通過斷點(diǎn)會(huì)發(fā)現(xiàn)執(zhí)行的是cache.fastInstanceSize

    size_t fastInstanceSize(size_t extra) const
    {
        ASSERT(hasFastInstanceSize(extra));

        if (__builtin_constant_p(extra) && extra == 0) {
            return _flags & FAST_CACHE_ALLOC_MASK16;
        } else {
            size_t size = _flags & FAST_CACHE_ALLOC_MASK;
            // remove the FAST_CACHE_ALLOC_DELTA16 that was added
            // by setFastInstanceSize
            return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
        }
    }

會(huì)發(fā)現(xiàn)最后返回align16

static inline size_t align16(size_t x) {
    return (x + size_t(15)) & ~size_t(15);
}

可以看到是返回的是一個(gè)16字節(jié)對(duì)齊算法
x為需要開辟多少內(nèi)存 +15 然后對(duì)與取反后的15進(jìn)行位與運(yùn)算

2)怎么申請(qǐng)內(nèi)存

calloc方法
po當(dāng)前obj后得出: 0x000000010114f040; 已經(jīng)開辟了內(nèi)存空間,但是發(fā)現(xiàn)只是有指針,并不是正常的對(duì)象打印,沒有與對(duì)象關(guān)聯(lián)

3)將開辟的內(nèi)存與對(duì)象綁定

obj->initInstanceIsa方法

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

此時(shí)在進(jìn)行一次 po obj
<LGPerson: 0x10114f040>

到這里就已經(jīng)完成了alloc的整個(gè)流程
可以得出alloc是開辟內(nèi)存的操作

init

+ (id)init {
    return (id)self;
}

可以看出 init將傳入的對(duì)象轉(zhuǎn)化了一個(gè)id類型的對(duì)象。
疑惑,為什么要alloc其實(shí)已經(jīng)完成了開辟內(nèi)存的操作,init構(gòu)造方法是不是多此一舉。
其實(shí),這樣做為工廠設(shè)計(jì)提供了便捷。為開發(fā)者提供了一個(gè)構(gòu)造方法的入口。

new

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

好像在哪見過,找一下,在alloc中的_objc_rootAlloc找到了

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

new方法是在callAlloc后添加了一個(gè)init方法
可以得出new = alloc init
所以在重寫init方法后,使用new并沒有調(diào)用重寫后的init。

流程圖
alloc流程圖

最后編輯于
?著作權(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ù)。

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