美文网首页iOS面试知识
0x004 理解iOS weak对象释放后置为nil原理

0x004 理解iOS weak对象释放后置为nil原理

作者: 小码农小世界 | 来源:发表于2021-01-20 14:55 被阅读0次

    理解iOS weak对象释放后置为nil原理

    weak对象dealloc流程图

    1、弱引用对象释放的浏览与普通对象释放流程基本一样,区别在于清除散列表。

    1)清除散列表入口方法sidetable_clearDeallocating

    void objc_object::sidetable_clearDeallocating()
    {
        SideTable& table = SideTables()[this];
        table.lock();
        RefcountMap::iterator it = table.refcnts.find(this);
        if (it != table.refcnts.end()) {
            if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) {
                weak_clear_no_lock(&table.weak_table, (id)this);
            }
            table.refcnts.erase(it);
        }
        table.unlock();
    }
    

    这里在散列表中找到当想对象的位置it,接着在弱引用表中删除弱引用对象,最后在散列表中清除it位置的数据;

    2)weak_clear_no_lock方法分享

    void weak_clear_no_lock(weak_table_t *weak_table, id referent_id) 
    {
        objc_object *referent = (objc_object *)referent_id;
    
        weak_entry_t *entry = weak_entry_for_referent(weak_table, referent);
        if (entry == nil) {
            return;
        }
        weak_referrer_t *referrers;
        size_t count;
        
        if (entry->out_of_line()) {
            referrers = entry->referrers;
            count = TABLE_SIZE(entry);
        } 
        else {
            referrers = entry->inline_referrers;
            count = WEAK_INLINE_COUNT;
        }
        for (size_t i = 0; i < count; ++i) {
            objc_object **referrer = referrers[i];
            if (referrer) {
                if (*referrer == referent) {
                    *referrer = nil;
                }
                else if (*referrer) {
                    _objc_inform("__weak variable at %p holds %p instead of %p. "
                                 "This is probably incorrect use of "
                                 "objc_storeWeak() and objc_loadWeak(). "
                                 "Break on objc_weak_error to debug.\n", 
                                 referrer, (void*)*referrer, (void*)referent);
                    objc_weak_error();
                }
            }
        }
        weak_entry_remove(weak_table, entry);
    }
    

    首先根据weak_entry_for_referent(weak_table, referent)对象在弱引用表中找到实体entry,取出实体中弱引用数组referrersreferrers存储的是弱引用指针地址,循环数组置空,最后在弱引用表中移除实体weak_entry_remove(weak_table, entry)

    相关文章

      网友评论

        本文标题:0x004 理解iOS weak对象释放后置为nil原理

        本文链接:https://www.haomeiwen.com/subject/tojkzktx.html