iOS dealloc 流程

dealloc 流程

一、_objc_rootDealloc

if (fastpath(isa.nonpointer  &&   // 0 普通指针 存放 类对象、元类对象内存地址
     !isa.weakly_referenced  &&  //无弱引用
     !isa.has_assoc  &&  //无关联对象
     !isa.has_cxx_dtor  &&  //无cxx析构函数
     !isa.has_sidetable_rc)) //无散列表引用计数
{
    assert(!sidetable_present());
    free(this); //直接释放
} 
else {
    object_dispose((id)this);//则作其余操做
}
复制代码

二、dispose

objc_destructInstance

​	是否有c++析构函数

​	是否存在关联对象

​	obj->clearDeallocating();

free
复制代码

三、clearDeallocating

weak_clear_no_lockc++

clearDeallocating函数首先根据对象地址获取全部weak指针地址的数组,而后遍历这个数组把其中的数据设为nil,最后把这个entry从weak表中删除,最后清理对象的记录。数组

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());
}
复制代码
objc_object::sidetable_clearDeallocating()
{
    SideTable& table = SideTables()[this];

    // clear any weak table items  清理weak 表
    // clear extra retain count and deallocating bit 清除引用计数

    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();
}
复制代码
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();
}
复制代码
相关文章
相关标签/搜索