__weak简析

作者: 三国韩信 | 来源:发表于2020-06-18 11:52 被阅读0次

弱引用在oc中被经常用到的,用__weak修饰的对象不会引用计数+1,不会被强引用。
那么__weak是怎么做到的呢,苹果在底层对__weak做了啥? now show code:

id objc_initWeak(id *location, id newObj)
{
    if (!newObj) {
        *location = nil;
        return nil;
    }
    return storeWeak<DontHaveOld, DoHaveNew, DoCrashIfDeallocating>
        (location, (objc_object*)newObj);
}

看源码发现,__weak调用了objc_initWeak这个方法,然后在函数体内又调用了storeWeak 这个函数,那么storeWeak是啥样的呢?

static id  storeWeak(id *location, objc_object *newObj)
{
    assert(haveOld  ||  haveNew);
    if (!haveNew) assert(newObj == nil);

    Class previouslyInitializedClass = nil;
    id oldObj;
    SideTable *oldTable;
    SideTable *newTable;

    // Acquire locks for old and new values.
    // Order by lock address to prevent lock ordering problems. 
    // Retry if the old value changes underneath us.
 retry:
    if (haveOld) {
        oldObj = *location;
        oldTable = &SideTables()[oldObj];
    } else {
        oldTable = nil;
    }
    if (haveNew) {
        newTable = &SideTables()[newObj];
    } else {
        newTable = nil;
    }

    SideTable::lockTwo<haveOld, haveNew>(oldTable, newTable);

    if (haveOld  &&  *location != oldObj) {
        SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
        goto retry;
    }

    // Prevent a deadlock between the weak reference machinery
    // and the +initialize machinery by ensuring that no 
    // weakly-referenced object has an un-+initialized isa.
    if (haveNew  &&  newObj) {
        Class cls = newObj->getIsa();
        if (cls != previouslyInitializedClass  &&  
            !((objc_class *)cls)->isInitialized()) 
        {
            SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
            _class_initialize(_class_getNonMetaClass(cls, (id)newObj));

            // If this class is finished with +initialize then we're good.
            // If this class is still running +initialize on this thread 
            // (i.e. +initialize called storeWeak on an instance of itself)
            // then we may proceed but it will appear initializing and 
            // not yet initialized to the check above.
            // Instead set previouslyInitializedClass to recognize it on retry.
            previouslyInitializedClass = cls;

            goto retry;
        }
    }

    // Clean up old value, if any.
    if (haveOld) {
        weak_unregister_no_lock(&oldTable->weak_table, oldObj, location);
    }

    // Assign new value, if any.
    if (haveNew) {
        newObj = (objc_object *)
            weak_register_no_lock(&newTable->weak_table, (id)newObj, location, 
                                  crashIfDeallocating);
        // weak_register_no_lock returns nil if weak store should be rejected

        // Set is-weakly-referenced bit in refcount table.
        if (newObj  &&  !newObj->isTaggedPointer()) {
            newObj->setWeaklyReferenced_nolock();
        }

        // Do not set *location anywhere else. That would introduce a race.
        *location = (id)newObj;
    }
    else {
        // No new value. The storage is not changed.
    }
    
    SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);

    return (id)newObj;
}

这里重点看一下第58行到76行的2个函数:weak_unregister_no_lock、weak_register_no_lock。

id  weak_register_no_lock(weak_table_t *weak_table, id referent_id, 
                      id *referrer_id, bool crashIfDeallocating)
{
    objc_object *referent = (objc_object *)referent_id;
    objc_object **referrer = (objc_object **)referrer_id;

    if (!referent  ||  referent->isTaggedPointer()) return referent_id;

    // ensure that the referenced object is viable
    bool deallocating;
    if (!referent->ISA()->hasCustomRR()) {
        deallocating = referent->rootIsDeallocating();
    }
    else {
        BOOL (*allowsWeakReference)(objc_object *, SEL) = 
            (BOOL(*)(objc_object *, SEL))
            object_getMethodImplementation((id)referent, 
                                           SEL_allowsWeakReference);
        if ((IMP)allowsWeakReference == _objc_msgForward) {
            return nil;
        }
        deallocating =
            ! (*allowsWeakReference)(referent, SEL_allowsWeakReference);
    }

    if (deallocating) {
        if (crashIfDeallocating) {
            _objc_fatal("Cannot form weak reference to instance (%p) of "
                        "class %s. It is possible that this object was "
                        "over-released, or is in the process of deallocation.",
                        (void*)referent, object_getClassName((id)referent));
        } else {
            return nil;
        }
    }

   /*这里是重点关注的代码,通过referent到weak_table里去找。
        1. 判断之前是否已经有弱引用过了,如果有则能找到entry,那么就把当前的若引用添加到entry里。
        2.若该对象是第一次被引用,则创建entry对象,并把当前的引用添加进去,
           判断weak_table是否到达3/4的容量界限,超过界限则2倍扩容weak_table。
           最后把当前新建的entry对象管理到weak_table表中
  */
    weak_entry_t *entry;
    if ((entry = weak_entry_for_referent(weak_table, referent))) {
        append_referrer(entry, referrer);
    } 
    else {
        weak_entry_t new_entry(referent, referrer);
        weak_grow_maybe(weak_table);
        weak_entry_insert(weak_table, &new_entry);
    }

    // Do not set *referrer. objc_storeWeak() requires that the 
    // value not change.

    return referent_id;
}

weak_unregister_no_lock:如果当前的引用referrer_id有引用过其他对象,则会把之前的引用关系在weak_table中删除。

void  weak_unregister_no_lock(weak_table_t *weak_table, id referent_id, 
                        id *referrer_id)
{
    objc_object *referent = (objc_object *)referent_id;
    objc_object **referrer = (objc_object **)referrer_id;

    weak_entry_t *entry;

    if (!referent) return;

    if ((entry = weak_entry_for_referent(weak_table, referent))) {
        remove_referrer(entry, referrer);
        bool empty = true;
        if (entry->out_of_line()  &&  entry->num_refs != 0) {
            empty = false;
        }
        else {
            for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) {
                if (entry->inline_referrers[i]) {
                    empty = false; 
                    break;
                }
            }
        }

        if (empty) {
            weak_entry_remove(weak_table, entry);
        }
    }

    // Do not set *referrer = nil. objc_storeWeak() requires that the 
    // value not change.
}

由此可见,__weak在底层只是做了一次weak_table表存储引用关系而已,并没有其他操作。(没有retian、没有引用计数器+1)
当对象执行dealloc方法的时候,在delloc方法中会去把当前对象的weak_table中的weak_entry_t清除掉,并把引用对象置为nil。流程图如下:

__weak流程图.png

盗用网上大神的图,侵权必删

相关文章

  • __weak简析

    当一个 __weak 类型的指针指向的对象被释放时,该指针会自动被置成nil,因此__weak关键字修饰的指针又被...

  • __weak简析

    弱引用在oc中被经常用到的,用__weak修饰的对象不会引用计数+1,不会被强引用。那么__weak是怎么做到的呢...

  • Swift-11.析构方法和内存管理

    本章包含内容: 析构过程原理 析构器实践 Swift语言的内存管理分析 weak引用(弱引用) unowned引用...

  • mybatis-spring解析

    1、概述 原生Mybatis源码简析(上)原生Mybatis源码简析(下)在介绍原生Mybatis源码简析文章中,...

  • 简析 Swift 的模块系统

    简析 Swift 的模块系统 简析 Swift 的模块系统

  • 简析Swift和C的交互

    简析Swift和C的交互 简析Swift和C的交互

  • 2018-11-20 weak实现原理 - 简书

    weak实现原理 - 简书

  • shiro原理简析+基于springboot基础实践

    1、shiro原理简析 原理简析: 1、subject支持不通调用获取用户信息 2、SecurityManager...

  • Spring Boot启动流程简析

    Spring Boot启动流程简析 木叶之荣,2017年12月 Spring Boot启动流程简析(一) Spri...

  • 简叙weak

    weak故名思义就是弱~与其相对应的不免想到strong。所以作为小受的weak它本身是一种非拥有的关系。 那什么...

网友评论

    本文标题:__weak简析

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