OC內(nèi)存管理--對象的生成與銷毀

原文鏈接OC內(nèi)存管理--對象的生成與銷毀

在iOS開發(fā)中了,我們每天都會使用+ alloc- init這兩個方進行對象的初始化。我們也這知道整個對象的初始化過程其實就是開辟一塊內(nèi)存空間,并且初始化isa_t結(jié)構(gòu)體的過程

alloc的實現(xiàn)

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

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

整個過程其實就是NSObjectcallAlloc方法的實現(xiàn)。

callAlloc

/*
 cls:CustomClass
 checkNil:是否檢查Cls
 allocWithZone:是否分配到指定空間,默認為false,內(nèi)部會對其進行優(yōu)化
*/
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false) {
    //沒有class或則checkNil為YES,返回空
    if (slowpath(checkNil && !cls)) return nil;

//確保只有Objective-C 2.0語言的文件所引用
#if __OBJC2__
    //判斷class有沒有默認的allocWithZone方法
    if (fastpath(!cls->ISA()->hasCustomAWZ())) {
        // class可以快速分配
        if (fastpath(cls->canAllocFast())) {
            //hasCxxDtor();是C++析構(gòu)函數(shù),判斷是否有析構(gòu)函數(shù)
            bool dtor = cls->hasCxxDtor();
            //申請class的內(nèi)存空間
            id obj = (id)calloc(1, cls->bits.fastInstanceSize());
            if (slowpath(!obj)) return callBadAllocHandler(cls);
            //初始化isa指針
            obj->initInstanceIsa(cls, dtor);
            return obj;
        }
        else {
            //使用class_createInstance創(chuàng)建class
            id obj = class_createInstance(cls, 0);
            if (slowpath(!obj)) return callBadAllocHandler(cls);
            return obj;
        }
    }
#endif
    
    //說明有默認的allocWithZone的方法,調(diào)用allocWithZone方法
    if (allocWithZone) return [cls allocWithZone:nil];
    return [cls alloc];
}

__OBJC2__下當前類有沒有默認的allocWithZone方法是通過hasCustomAWZ()函數(shù)判斷的。YES代表有則會調(diào)用[cls allocWithZone:nil]方法。NO代表沒有,這時候會根據(jù)當前類是否可以快速分配,NO的話調(diào)用class_createInstance函數(shù);YES則分配內(nèi)存并初始化isa。

allocWithZone

+ (id)allocWithZone:(struct _NSZone *)zone {
    return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone);
}

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

allocWithZone函數(shù)的本質(zhì)是調(diào)用_objc_rootAllocWithZone函數(shù)。

_objc_rootAllocWithZone的邏輯分為兩種情況:

  1. 先判斷是否是__OBJC2__,如果是則調(diào)用class_createInstance
  2. 判斷zone是否為空,如果為空調(diào)用class_createInstance,如果不為空,調(diào)用class_createInstanceFromZone。
//class_createInstance
id class_createInstance(Class cls, size_t extraBytes) {
    return _class_createInstanceFromZone(cls, extraBytes, nil);
}

//class_createInstanceFromZone
id class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone) {
    return _class_createInstanceFromZone(cls, extraBytes, zone);
}

class_createInstanceclass_createInstanceFromZone的本質(zhì)都是調(diào)用_class_createInstanceFromZone。

另外通過前面的源代碼我們可以發(fā)現(xiàn):用alloc方式創(chuàng)建,只要當前類有allocWithZone方法,最終一定是調(diào)用class_createInstance。

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

    bool hasCxxCtor = cls->hasCxxCtor();//構(gòu)造函數(shù)
    bool hasCxxDtor = cls->hasCxxDtor();//析構(gòu)函數(shù)
    bool fast = cls->canAllocNonpointer(); //是對isa的類型的區(qū)分,如果一個類不能使用isa_t類型的isa的話,fast就為false,但是在Objective-C 2.0中,大部分類都是支持的
    //在分配內(nèi)存之前,需要知道對象在內(nèi)存中的大小,也就是instanceSize的作用。對象必須大于等于16字節(jié)。
    size_t size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (!zone  &&  fast) {
        //分配內(nèi)存空間
        obj = (id)calloc(1, size);
        if (!obj) return nil;
        //初始化isa指針
        obj->initInstanceIsa(cls, hasCxxDtor);
    } else {
        //此時的fast 為 false
        //在C語言中,malloc表示在內(nèi)存的動態(tài)存儲區(qū)中分配一塊長度為“size”字節(jié)的連續(xù)區(qū)域,返回該區(qū)域的首地址;calloc表示在內(nèi)存的動態(tài)存儲區(qū)中分配n塊長度為“size”字節(jié)的連續(xù)區(qū)域,返回首地址。
        if (zone) {
            obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size);
        } else {
            obj = (id)calloc(1, size);
        }
        if (!obj) return nil;

        //初始化isa指針
        obj->initIsa(cls);
    }

    if (cxxConstruct && hasCxxCtor) {
        obj = _objc_constructOrFree(obj, cls);
    }

    return obj;
}

初始化isa

_class_createInstanceFromZone中不光開辟了內(nèi)存空間,還初始化了isa。初始化isa的方法有initInstanceIsainitIsa,但是本質(zhì)都是調(diào)用initIsa(Class cls, bool nonpointer, bool hasCxxDtor)

inline void objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor) 
{ 
    assert(!isTaggedPointer()); 
    
    if (!nonpointer) {
        isa.cls = cls; //obj->initIsa(cls)
    } else {
        //obj->initInstanceIsa(cls, hasCxxDtor);
        assert(!DisableNonpointerIsa);
        assert(!cls->instancesRequireRawIsa());

        isa_t newisa(0);

#if SUPPORT_INDEXED_ISA
        assert(cls->classArrayIndex() > 0);
        newisa.bits = ISA_INDEX_MAGIC_VALUE;
        // isa.magic is part of ISA_MAGIC_VALUE
        // isa.nonpointer is part of ISA_MAGIC_VALUE
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.indexcls = (uintptr_t)cls->classArrayIndex();
#else
        newisa.bits = ISA_MAGIC_VALUE;
        // isa.magic is part of ISA_MAGIC_VALUE
        // isa.nonpointer is part of ISA_MAGIC_VALUE
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.shiftcls = (uintptr_t)cls >> 3;
#endif

        // This write must be performed in a single store in some cases
        // (for example when realizing a class because other threads
        // may simultaneously try to use the class).
        // fixme use atomics here to guarantee single-store and to
        // guarantee memory order w.r.t. the class index table
        // ...but not too atomic because we don't want to hurt instantiation
        isa = newisa;
    }
}

根據(jù)《OC引用計數(shù)器的原理》,現(xiàn)在再看一下初始化isa的方法。這個方法的意思是首先判斷是否開啟指針優(yōu)化。

沒有開啟指針優(yōu)化的話訪問 objc_objectisa會直接返回isa_t結(jié)構(gòu)中的cls變量,cls變量會指向?qū)ο笏鶎俚念惖慕Y(jié)構(gòu)。

開啟指針優(yōu)化的話通過newisa(0)函數(shù)初始化一個isa,并根據(jù)SUPPORT_INDEXED_ISA分別設(shè)置對應(yīng)的值。iOS設(shè)備的話這個值是0,所以執(zhí)行else的代碼。

到這里alloc的實現(xiàn)過程已經(jīng)結(jié)束了,根據(jù)上面的源碼分析,用一張圖表示上述過程:
image

這里可能會有個疑問,既然alloc將分配內(nèi)存空間和初始化isa的事情都做了,那么init的作用是什么呢?

init

- (id)init {
    return _objc_rootInit(self);
}

id _objc_rootInit(id obj) {
    return obj;
}

init的作用就是返回當前對象。這里有個問題既然init只是返回當前對象,為什么要多此一舉呢?

Apple給出的注釋:

In practice, it will be hard to rely on this function. Many classes do not properly chain -init calls.

意思是在實踐中,很難依靠這個功能。許多類沒有正確鏈接init調(diào)用。所以這個函數(shù)很可能不被調(diào)用。也許是歷史遺留問題吧。

new

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

所以說UIView *view = [UIView new];UIView *view = [[UIView alloc]init];是一樣的。

dealloc

分析了對象的生成,我們現(xiàn)在看一下對象是如何被銷毀的。dealloc的實現(xiàn)如下:

- (void)dealloc {
    _objc_rootDealloc(self);
}

void _objc_rootDealloc(id obj) {
    assert(obj);
    obj->rootDealloc();
}

inline void
objc_object::rootDealloc() {
    if (isTaggedPointer()) return;  // fixme necessary?

    if (fastpath(isa.nonpointer  &&  
                 !isa.weakly_referenced  &&  
                 !isa.has_assoc  &&  
                 !isa.has_cxx_dtor  &&  
                 !isa.has_sidetable_rc))
    {
        assert(!sidetable_present());
        free(this);
    } 
    else {
        object_dispose((id)this);
    }
}

rootDealloc分為三種情況:

  1. 如果是TaggedPointer,直接return;
  2. 進行一些關(guān)于isa的條件判斷,如果滿足就釋放分配的內(nèi)存控件;
  3. 調(diào)用object_dispose函數(shù),這是最重要的;

objc_destructInstance

我們先看object_dispose函數(shù)的源碼:

id object_dispose(id obj) {
    if (!obj) return nil;

    objc_destructInstance(obj);    
    free(obj);

    return nil;
}

做了兩件事情:

  1. 調(diào)用objc_destructInstance函數(shù)
  2. 釋放分配的內(nèi)存空間

objc_destructInstance的實現(xiàn)如下:

/***********************************************************************
* objc_destructInstance
* Destroys an instance without freeing memory. 
* Calls C++ destructors.
* Calls ARC ivar cleanup.
* Removes associative references.
* Returns `obj`. Does nothing if `obj` is nil.
**********************************************************************/
void *objc_destructInstance(id obj) 
{
    if (obj) {
        // Read all of the flags at once for performance.
        bool cxx = obj->hasCxxDtor();//是否有析構(gòu)函數(shù)
        bool assoc = obj->hasAssociatedObjects();//是否有關(guān)聯(lián)對象

        // This order is important.
        if (cxx) object_cxxDestruct(obj);//調(diào)用析構(gòu)函數(shù)
        if (assoc) _object_remove_assocations(obj);//刪除關(guān)聯(lián)對象
        obj->clearDeallocating();//清空引用計數(shù)表并清除弱引用表
    }

    return obj;
}

objc_destructInstance做了三件事情:

  1. 執(zhí)行object_cxxDestruct調(diào)用析構(gòu)函數(shù)
  2. 執(zhí)行_object_remove_assocations刪除關(guān)聯(lián)對象
  3. 執(zhí)行clearDeallocating清空引用計數(shù)表并清除弱引用表,將所有weak引用指nil(這也解釋了為什么使用weak能自動置空)

object_cxxDestruct

在源碼中object_cxxDestruct的實現(xiàn)由object_cxxDestructFromClass完成。

static void object_cxxDestructFromClass(id obj, Class cls)
{
    void (*dtor)(id);

    // Call cls's dtor first, then superclasses's dtors.

    for ( ; cls; cls = cls->superclass) {
        if (!cls->hasCxxDtor()) return; 
        dtor = (void(*)(id))
            lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct);
        if (dtor != (void(*)(id))_objc_msgForward_impcache) {
            if (PrintCxxCtors) {
                _objc_inform("CXX: calling C++ destructors for class %s", 
                             cls->nameForLogging());
            }
            (*dtor)(obj);
        }
    }
}

這段代碼的意思就是沿著繼承鏈逐層向上搜尋SEL_cxx_destruct這個selector,找到函數(shù)實現(xiàn)(void (*)(id)(函數(shù)指針)并執(zhí)行。說白了就是找析構(gòu)函數(shù),并執(zhí)行析構(gòu)函數(shù)。

析構(gòu)函數(shù)中書如何處理成員變量的?

  1. 對于strong來說執(zhí)行objc_storeStrong(&ivar, nil)release舊對象,ivar賦新值nil;
  2. 對于weak來說執(zhí)行objc_destroyWeak(&ivar)消除對象weak表中的ivar地址。

關(guān)于這個函數(shù)Sunnyxx ARC下dealloc過程及.cxx_destruct的探究中也有提到。

用一張圖表示dealloc的流程:

image

至于dealloc的調(diào)用時機,是跟引用計數(shù)器相關(guān)的。

?著作權(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ù)。

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

  • Objective-C語言是一門動態(tài)語言,他將很多靜態(tài)語言在編譯和鏈接時期做的事情放到了運行時來處理。這種動態(tài)語言...
    tigger丨閱讀 1,602評論 0 8
  • 本文轉(zhuǎn)載自:http://southpeak.github.io/2014/10/25/objective-c-r...
    idiot_lin閱讀 1,044評論 0 4
  • Objective-C語言是一門動態(tài)語言,它將很多靜態(tài)語言在編譯和鏈接時期做的事放到了運行時來處理。這種動態(tài)語言的...
    有一種再見叫青春閱讀 682評論 0 3
  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 2,083評論 0 9
  • 感謝那些偷偷愛著我,關(guān)心著我的親人、朋友以及陌生人。
    驪風(fēng)云翳閱讀 204評論 0 0

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