【iOS底层了解一点】-01 Dealloc流程

403 阅读1分钟

参考底层源码:objc4-818.2

第一步:调用NSObject的dealloc方法

- (void)dealloc {
    _objc_rootDealloc(self); 
}

第二步:_objc_rootDealloc函数

void _objc_rootDealloc(id obj) {
   ASSERT(obj); obj->rootDealloc(); 
}

第三步:主要是调用了rootDealloc方法

inline void
objc_object::rootDealloc()
{
    //如果是taggedPoint类型的数据,它本身是被系统优化的,没有开辟再堆上,不需要处理回收,直接不处理
    if (isTaggedPointer()) return// fixme necessary?
    
    //会直接释放的条件:是优化的指针 && 没有被弱引用引用过 &&
    //没有关联对象 && 没有自定义西沟函数函数 && 实例对象没有存在dealloc方法 && 没有启用sidetable保存引用技术
    if (fastpath(isa.nonpointer                     &&
                 !isa.weakly_referenced             &&
                 !isa.has_assoc                     &&
#if ISA_HAS_CXX_DTOR_BIT
                 !isa.has_cxx_dtor                  &&
#else
                 !isa.getClass(**false**)->hasCxxDtor() &&
#endif
                 !isa.has_sidetable_rc))
    {
        assert(!sidetable_present());
        free(**this**);
    } else {/*如果满足前面的任意一个条件就会在object_dispose函数李处理*/

        object_dispose((**id**)**this**);

    }

}

第四步:object_dispose

/***********************************************************************
* object_dispose
* fixme
* Locking: none
**************************************************************************/
id object_dispose(id obj)
{
    if (!obj) return nil;
    objc_destructInstance(obj);
    free(obj);
    return nil;
}

4.1 objc_destructInstance 函数

/***********************************************************************
* objc_destructInstance
* Destroys an instance without freeing memory.
* Calls C++ destructors.
* Calls ARC ivar cleanup.
* Removes associative references.
* Returns `obj`. Does nothing if `obj` is 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, /*deallocating*/true);
        obj->clearDeallocating();

    }
    
    return obj;
}
  • 销毁所有的c++变量
  • 如果存在关联会_object_remove_assocations在函数里去AssociationManage里处理

4.2 clearDeallocating函数移除跟自己形成弱引用关系的指针对象

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());
}
  • 在全局的SideTables找到对象关联的Sidetable
  • 在指定的sideTable里找到weak_table
  • 在指定的weak_table找到weak_entry_t
  • 在指定的额weak_entry_t里移除当前对象refreter对应的refreshers列表
  • weak_entry_t移除它所在的weak_table