# iOS weak弱引用实现原理以及释放原理。

iOS weak 原理

直接看源码


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

上篇文章提到 isa 指针的结构,如果看过的人,对前面的 if 语句,一看便知,如果是非指针型 isa 并且 没有弱引用并且没有关联对象并且C++函数并且没有sidetable存储表,那么就直接释放。

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

    objc_destructInstance(obj);    
    free(obj);

    return nil;
}



 void *objc_destructInstance(id obj) 
{
    if (obj) {
        // Read all of the flags at once for performance.
        bool cxx = obj->hasCxxDtor();
        bool assoc = obj->hasAssociatedObjects();

        // This order is important.
        if (cxx) object_cxxDestruct(obj);
        if (assoc) _object_remove_assocations(obj);
        obj->clearDeallocating();
    }

    return obj;
}





inline void 
objc_object::clearDeallocating()
{
    if (slowpath(!isa.nonpointer)) {
        // Slow path for raw pointer isa.
        sidetable_clearDeallocating();
    }
    else if (slowpath(isa.weakly_referenced  ||  isa.has_sidetable_rc)) {
        // Slow path for non-pointer isa with weak refs and/or side table data.
        clearDeallocating_slow();
    }

    assert(!sidetable_present());
}


NEVER_INLINE void
objc_object::clearDeallocating_slow()
{
    assert(isa.nonpointer  &&  (isa.weakly_referenced || isa.has_sidetable_rc));

    SideTable& table = SideTables()[this];
    table.lock();
    if (isa.weakly_referenced) {
        weak_clear_no_lock(&table.weak_table, (id)this);
    }
    if (isa.has_sidetable_rc) {
        table.refcnts.erase(this);
    }
    table.unlock();
}



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) {
        /// XXX shouldn't happen, but does with mismatched CF/objc
        //printf("XXX no entry for clear deallocating %p\n", referent);
        return;
    }

    // zero out references
    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);
}



可以看到最后,移除弱引用的操作,

 if (isa.weakly_referenced) {
        weak_clear_no_lock(&table.weak_table, (id)this);
    }

从代码中可以看出,首先 SideTable& table = SideTables()[this]; 从 SideTables 中,通过hash运算找到对应的 SideTable ,我们来看下我们的 SideTable 的结构

struct SideTable {
    spinlock_t slock;
    RefcountMap refcnts;
    weak_table_t weak_table;

里面有个 weak_table 的结构,这个结构体

struct weak_table_t {
    weak_entry_t *weak_entries;
    size_t    num_entries;
    uintptr_t mask;
    uintptr_t max_hash_displacement;
};

里面存储着 weak_entries ,也就是弱引用表,当我们找到对应的 SideTable 之后,然后拿到这个 SideTable 中的 weaktable,也就是弱引用表,然后去找对应的 weak_entry_t , 因为 weaktable 里面存储着 weak_entry_t , 所以,通过 hash 就能拿到对应的弱引用结构,然后最后从我们的弱引用表里面清除就可以了。

从代码中也不难看出有弱引用,会调用另一个方法,然后 weak_entry_t *entry = weak_entry_for_referent(weak_table, referent); 去找到弱引用表,最后调用 weak_entry_remove(weak_table, entry); 移除弱引用。接着判断是否有引用计数表吗,如果有也擦除掉,这就是为什么 weak 指针会自动释放。

总结,其实如果存在弱引用,系统会将这些弱引用存储到一个 hash 表里面,并把 isa 指针弱引用的值设置为1,当销毁的时候,会找到这个弱引用表然后移除弱引用,擦除引用计数。

你可能感兴趣的:(# iOS weak弱引用实现原理以及释放原理。)