OC--看objc源碼認識retain、release、dealloc

NSObject.mm源碼

對象--id
typedef struct objc_object *id;
struct objc_object {
    isa_t _Nonnull isa  OBJC_ISA_AVAILABILITY;
};
arm64 架構中的 isa_t 結構體 (bits格式一樣,一些信息的位數不一樣)
union isa_t {
    isa_t() { }
    isa_t(uintptr_t value) : bits(value) { }

    Class cls;
    uintptr_t bits;

# if __arm64__
#   define ISA_MASK        0x0000000ffffffff8ULL
#   define ISA_MAGIC_MASK  0x000003f000000001ULL
#   define ISA_MAGIC_VALUE 0x000001a000000001ULL
    struct {
       uintptr_t nonpointer        : 1;  // 0 表示普通的 isa 指針,1 表示使用優化,存儲引用計數
       uintptr_t has_assoc         : 1;  // 表示該對象是否包含 associated object,如果沒有,則析構時會更快
       uintptr_t has_cxx_dtor      : 1;  // 表示該對象是否有 C++ 或 ARC 的析構函數,如果沒有,則析構時更快
       uintptr_t shiftcls          : 33; // 類的指針
       uintptr_t magic             : 6;  // 固定值為 0xd2,用于在調試時分辨對象是否未完成初始化。
       uintptr_t weakly_referenced : 1;  // 表示該對象是否有過 weak 對象,如果沒有,則析構時更快
       uintptr_t deallocating      : 1;  // 表示該對象是否正在析構
       uintptr_t has_sidetable_rc  : 1;  // 標記是否在 sidetable 中存有引用計數
       uintptr_t extra_rc          : 19; // 存儲引用計數值減一后的結果
#      define RC_ONE   (1ULL<<45)
#      define RC_HALF  (1ULL<<18)
    };
};
引用計數

iOS引用計數管理之揭秘計數存儲

現在一個對象的引用計數管理有三種情況:
1、TaggedPointer -- 深入理解Tagged Pointer
2、非nonpointer -- 純SideTable管理引用計數
3、nonpointer( 64 位設備的指針優化)--(bits.extra_rc + SideTable)管理引用計數,(isa指針是占64位的,類的指針bits.shiftcls只占用33位,為了提高利用率,剩余的存儲內存管理的相關數據內容)

TaggedPointer的對象

對于 64 位程序,為了節省內存和提高執行效率,蘋果提出了Tagged Pointer的概念。
1、可以啟用Tagged Pointer的類對象有:NSDate、NSNumber、NSString。Tagged Pointer專門用來存儲小的對象。
2、Tagged Pointer指針的值不再是地址了,而是真正的值。所以,實際上它不再是一個對象了,它只是一個披著對象皮的普通變量而已。創建讀取效率非常快。
3、在環境變量中設置OBJC_DISABLE_TAGGED_POINTERS=YES強制不啟用Tagged Pointer。

nonpointer

nonpointer:在64位系統中,為了降低內存使用,提升性能,isa中有一部分字段用來存儲其他信息。

RetainCount源碼,直接體現了三種情況
inline uintptr_t 
objc_object::rootRetainCount()
{
    if (isTaggedPointer()) return (uintptr_t)this; // ??1、TaggedPointer

    sidetable_lock();
    isa_t bits = LoadExclusive(&isa.bits);
    ClearExclusive(&isa.bits);
    if (bits.nonpointer) { // ??3、nonpointer--(bits.extra_rc + SideTable)管理引用計數
        uintptr_t rc = 1 + bits.extra_rc;
        if (bits.has_sidetable_rc) {
            rc += sidetable_getExtraRC_nolock();
        }
        sidetable_unlock();
        return rc;
    }

    sidetable_unlock();
    return sidetable_retainCount(); // ??2、純SideTable
}

2、SideTable

內存管理主要結構代碼

struct SideTable {
    spinlock_t slock; // 保證原子操作的自旋鎖
    RefcountMap refcnts; // 引用計數的 hash 表
    weak_table_t weak_table; // weak 引用全局 hash 表
};

retainCount 是保存在一個無符號整形中


位數相關
uintptr_t
objc_object::sidetable_retainCount()
{
    SideTable& table = SideTables()[this];
    size_t refcnt_result = 1;
    
    table.lock();
    RefcountMap::iterator it = table.refcnts.find(this);
    if (it != table.refcnts.end()) {
        // it->second 無符號整型(上面的圖),真實的引用計數需要右移2位
        refcnt_result += it->second >> SIDE_TABLE_RC_SHIFT;
    }
    table.unlock();
    return refcnt_result;
}

retain源碼

id
objc_object::sidetable_retain()
{
#if SUPPORT_NONPOINTER_ISA
    assert(!isa.nonpointer);
#endif
    SideTable& table = SideTables()[this];
    
    table.lock();
    size_t& refcntStorage = table.refcnts[this];
    // 判斷是否溢出,溢出了就是引用計數太大了,不管理了
    if (! (refcntStorage & SIDE_TABLE_RC_PINNED)) {
        // 引用計數加1,(上圖可知,偏移2位,SIDE_TABLE_RC_ONE = 1<<2)
        refcntStorage += SIDE_TABLE_RC_ONE;
    }
    table.unlock();
    return (id)this;
}

release源碼

uintptr_t
objc_object::sidetable_release(bool performDealloc)
{
#if SUPPORT_NONPOINTER_ISA
    assert(!isa.nonpointer);
#endif
    SideTable& table = SideTables()[this];

    bool do_dealloc = false;

    table.lock();
    RefcountMap::iterator it = table.refcnts.find(this);
    if (it == table.refcnts.end()) {
        // ??(1)對象沒有引用計數(沒有被強引用)
        do_dealloc = true;
        // 標記dealloc(上圖的第二位)
        table.refcnts[this] = SIDE_TABLE_DEALLOCATING;
    } else if (it->second < SIDE_TABLE_DEALLOCATING) {
        // ??(2)引用計數為0
        do_dealloc = true;
        // 標記dealloc(上圖的第二位,或運算),
        it->second |= SIDE_TABLE_DEALLOCATING;
    } else if (! (it->second & SIDE_TABLE_RC_PINNED)) {
        // ??(3)正常引用計數減1,(上圖可知,偏移2位,SIDE_TABLE_RC_ONE = 1<<2)
        it->second -= SIDE_TABLE_RC_ONE;
    }
    table.unlock();
    if (do_dealloc  &&  performDealloc) {
        // ??(4)do_dealloc為真,執行dealloc方法
        ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc);
    }
    return do_dealloc;
}

看后面幾個判斷。
(1) 如果對象記錄在引用計數表的最后一個(對象沒有引用計數):do_dealloc 設置為 true,引用計數數值設置為 SIDE_TABLE_DEALLOCATING(二進制 00000010)。
(2) 如果引用計數小于 SIDE_TABLE_DEALLOCATING(就是引用計數等于0),標記dealloc。
(3) 如果引用計數大于>=1, 就it->second -= SIDE_TABLE_RC_ONE;就是-1。
(4) 如果 do_dealloc 和 performDealloc(傳入時就已經為 true)都為 ture,執行 SEL_dealloc 釋放對象。方法返回 do_dealloc。
(5)調用父類dealloc,直到根類NSobject

3、nonpointer(bits.extra_rc + SideTable)

retain源碼

ALWAYS_INLINE id 
objc_object::rootRetain(bool tryRetain, bool handleOverflow)
{
    //?????? 1、TaggedPointer
    if (isTaggedPointer()) return (id)this;

    bool sideTableLocked = false;
    bool transcribeToSideTable = false;

    isa_t oldisa;
    isa_t newisa;

    do {
        transcribeToSideTable = false;
        oldisa = LoadExclusive(&isa.bits);
        newisa = oldisa;
        if (slowpath(!newisa.nonpointer)) {
            //?????? 2、純SideTable散列表方法
            ClearExclusive(&isa.bits);
            if (!tryRetain && sideTableLocked) sidetable_unlock();
            if (tryRetain) return sidetable_tryRetain() ? (id)this : nil;
            else return sidetable_retain();
        }
        if (slowpath(tryRetain && newisa.deallocating)) {
            // 正在釋放
            ClearExclusive(&isa.bits);
            if (!tryRetain && sideTableLocked) sidetable_unlock();
            return nil;
        }

        //?????? 3、nonpointer(isa.extra_rc+ SideTable)
        uintptr_t carry;
        newisa.bits = addc(newisa.bits, RC_ONE, 0, &carry);  // 應用計數extra_rc++
        // 如果newisa.extra_rc++ 溢出, carry==1
        if (slowpath(carry)) {
            // 溢出
            if (!handleOverflow) {
                ClearExclusive(&isa.bits); // 空操作(系統預留)
                return rootRetain_overflow(tryRetain);// 再次調用rootRetain(tryRetain,YES)
            }
            // 執行rootRetain_overflow會來到這里,就把extra_rc對應的數值(一半)存到SideTable
            if (!tryRetain && !sideTableLocked) sidetable_lock();
            sideTableLocked = true;
            transcribeToSideTable = true;
            newisa.extra_rc = RC_HALF; // 溢出了,設置為一半,保存一半到SideTable
            newisa.has_sidetable_rc = true; // 標記借用SideTable存儲
        }
        // StoreExclusive保存newisa.bits到isa.bits,保存成功返回YES
        // 這里while判斷一次就結束了
    } while (slowpath(!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)));

    if (slowpath(transcribeToSideTable)) {
        // 借位保存:把RC_HALF(一半)存入SideTable
        sidetable_addExtraRC_nolock(RC_HALF);
    }

    if (slowpath(!tryRetain && sideTableLocked)) sidetable_unlock();
    return (id)this;
}

這個方法挺簡單的:
1、其實就是引用計數extra_rc++;
2、extra_rc滿了存一半到SideTable(arm64的extra_rc是19位,完全夠存)

借位保存方法
bool 
objc_object::sidetable_addExtraRC_nolock(size_t delta_rc)
{
    assert(isa.nonpointer);
    SideTable& table = SideTables()[this];

    size_t& refcntStorage = table.refcnts[this];
    size_t oldRefcnt = refcntStorage;
    // isa-side bits should not be set here
    assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0);
    assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0);

    // 系統計數極限了,直接true
    if (oldRefcnt & SIDE_TABLE_RC_PINNED) return true;

    uintptr_t carry;
    size_t newRefcnt = 
        addc(oldRefcnt, delta_rc << SIDE_TABLE_RC_SHIFT, 0, &carry);

    if (carry) {
        // 如果借位保存在這里還溢出,就當做SIDE_TABLE_RC_PINNED次數(32或64最大位數-1的數值)
        refcntStorage =
            SIDE_TABLE_RC_PINNED | (oldRefcnt & SIDE_TABLE_FLAG_MASK);
        return true;
    }
    else {
        refcntStorage = newRefcnt;
        return false;
    }
}
release源碼
ALWAYS_INLINE bool 
objc_object::rootRelease(bool performDealloc, bool handleUnderflow)
{
    if (isTaggedPointer()) return false;

    bool sideTableLocked = false;

    isa_t oldisa;
    isa_t newisa;

 retry:
    do {
        oldisa = LoadExclusive(&isa.bits);
        newisa = oldisa;
        if (slowpath(!newisa.nonpointer)) {
            // 這是2、SideTable散列表的
            ClearExclusive(&isa.bits);
            if (sideTableLocked) sidetable_unlock();
            return sidetable_release(performDealloc);
        }
        uintptr_t carry;
        newisa.bits = subc(newisa.bits, RC_ONE, 0, &carry);  // extra_rc--
        // 如果extra_rc==0,extra_rc--會是負數,carry=1
        if (slowpath(carry)) {
            goto underflow;
        }
    } while (slowpath(!StoreReleaseExclusive(&isa.bits, 
                                             oldisa.bits, newisa.bits)));

    if (slowpath(sideTableLocked)) sidetable_unlock();
    return false;

 underflow:
    // newisa重新賦值
    newisa = oldisa;

    
    if (slowpath(newisa.has_sidetable_rc)) {
        // 有借位保存,rootRelease_underflow重新進入函數
        if (!handleUnderflow) {
            ClearExclusive(&isa.bits);
            return rootRelease_underflow(performDealloc);
        }
        
        // 一些鎖的操作
        if (!sideTableLocked) {
            ClearExclusive(&isa.bits);
            sidetable_lock();
            sideTableLocked = true;
            goto retry;
        }

        // 獲取借位引用次數,(獲取次數最大RC_HALF)
        size_t borrowed = sidetable_subExtraRC_nolock(RC_HALF);
        if (borrowed > 0) {
            
            // extra_rc--
            newisa.extra_rc = borrowed - 1;
            // 保存,就是StoreExclusive
            // 如果&isa.bits和oldisa.bits相等,那么就把newisa.bits的值賦給&isa.bits,并且返回true
            bool stored = StoreReleaseExclusive(&isa.bits, 
                                                oldisa.bits, newisa.bits);
            if (!stored) {
                // 保存失敗,重新試一次(重復的代碼)
                isa_t oldisa2 = LoadExclusive(&isa.bits);
                isa_t newisa2 = oldisa2;
                if (newisa2.nonpointer) {
                    uintptr_t overflow;
                    newisa2.bits = 
                        addc(newisa2.bits, RC_ONE * (borrowed-1), 0, &overflow);
                    if (!overflow) {
                        stored = StoreReleaseExclusive(&isa.bits, oldisa2.bits, 
                                                       newisa2.bits);
                    }
                }
            }

            if (!stored) {
                // 還是不成功,把次數放回SideTable,重試retry
                sidetable_addExtraRC_nolock(borrowed);
                goto retry;
            }
            // release結束
            sidetable_unlock();
            return false;
        }
        else {
            // 如果sidetable也有沒有次數,然后就到下面dealloc階段了
        }
    }

    // 如果沒有借位保存次數,來到這里

    if (slowpath(newisa.deallocating)) {
        // 如果對象已經正在釋放,報錯警告:多次release
        ClearExclusive(&isa.bits);
        if (sideTableLocked) sidetable_unlock();
        return overrelease_error();
    }
    newisa.deallocating = true;
    // 保存bits
    if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry;

    if (slowpath(sideTableLocked)) sidetable_unlock();

    __sync_synchronize();
    if (performDealloc) {
        // 調用dealloc
        ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc);
    }
    return true;
}

NSobject dealloc源碼

NSObject dealloc流程圖
void *objc_destructInstance(id obj) 
{
    if (obj) {
        bool cxx = obj->hasCxxDtor();
        bool assoc = obj->hasAssociatedObjects();
        if (cxx) object_cxxDestruct(obj);
        if (assoc) _object_remove_assocations(obj);
        obj->clearDeallocating();
    }
    return obj;
}

簡單明確的干了三件事:
1、執行object_cxxDestruct,處理本類的成員變量(父類的由父類處理)。
object_cxxDestruct里面最終for ( ; cls; cls = cls->superclass){執行.cxx_destruct};
cxx_destruct最后執行處理成員變量:
① strong的objc_storeStrong(&ivar, nil)release對象,ivar賦值nil,
② weak的objc_destroyWeak(& ivar)消除對象weak表中的ivar地址。

2、執行_object_remove_assocations去除和這個對象assocate的對象(常用于category中添加帶變量的屬性,這也是為什么沒必要remove一遍的原因。

3、執行objc_clear_deallocating,清空引用計數表并清除弱引用表,將所有weak引用指nil(這也就是weak變量能安全置空的所在)。

對象釋放過程的簡單總結--dealloc

1. 調用 -release :isa.bits.extra_rc由0繼續減一時候觸發dealloc,
   (1)標記對象isa.deallocating = true,對象正在銷毀,生命周期即將結束,不能再有新的 weak 弱引用
   (2)調用 [self dealloc] (MRC需要在dealloc方法中手動釋放強引用的變量)
   (3)superclass都調用dealloc,一直到根類(NSObject)

2. 根類 NSObject 調 dealloc -> object_dispose()
   (1)objc_destructInstance(obj); 
   (2)free(obj);

3. objc_destructInstance(obj)執行三個操作
    (1)if (cxx) object_cxxDestruct(obj); // 釋放變量
        ① strong ivar 執行objc_storeStrong(&ivar, nil)release對象,ivar賦值nil,
        ② weak ivar 執行objc_destroyWeak(&ivar) >> storeWeak(&ivar, nil) 將ivar指向nil且ivar的地址從對象的weak表中刪除。
    (2)if (assoc) _object_remove_assocations(obj); // 移除Associate關聯數據(這就是不需要手動移除的原因)
    (3)obj->clearDeallocating(); // 清空weak變量表且將所有引用指向nil、清空引用計數表
        ① 執行 weak_clear_no_lock:清空weak變量表且將所有引用指向nil
        ② 執行 table.refcnts.eraser:清空相關SideTable的引用計數表。

objc_storeStrong源碼

是對一個strong指針再次賦值,比如

NSObject *obj = [NSObject new];
NSObject *obj2 = [NSObject new];
NSObject *strongObj = obj;
strongObj = obj2;//執行objc_storeStrong(&strongObj, obj2);

{
    NSObject *obj = [NSObject new];
} // 出了作用域,執行objc_storeStrong(&obj, nil);
void
objc_storeStrong(id *location, id obj)
{
    // 1、當前strong指針指向的位置找到舊對象,
    id prev = *location;
    if (obj == prev) {
        return;
    }
    objc_retain(obj);// 2、新對象執行retain,指針指向新對象,
    *location = obj;
    objc_release(prev); //3、 release舊對象
}

參考:
iOS進階——iOS(Objective-C)內存管理·二
ARC下dealloc過程及.cxx_destruct的探究

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容