objc4源码解析&dealloc

159 阅读1分钟

objc4源码基于779.1版本。文章纯属个人学习见解,谬误之处,望指正。

dealloc

方法调用栈

  • (void)dealloc
    • void _objc_rootDealloc(id obj)
      • inline void objc_object::rootDealloc()
        • id object_dispose(id obj)
          • void *objc_destructInstance(id obj)
            • object_cxxDestruct()
            • _object_remove_assocations()
            • clearDeallocating()

源码详注

  1. NSObject.mm line:2341
- (void)dealloc {
    _objc_rootDealloc(self);
}
  1. NSObject.mm line:1814
void
_objc_rootDealloc(id obj)
{
    ASSERT(obj);

    obj->rootDealloc();
}
  1. objc-object.h line:434
inline void
objc_object::rootDealloc()
{
    // 是TaggedPointer直接返回
    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);
    }
}
  1. objc-runtime-new.mm line:7565
id 
object_dispose(id obj)
{
    if (!obj) return nil;

    // 销毁实例
    objc_destructInstance(obj);
    // 释放内存
    free(obj);

    return nil;
}
  1. objc-runtime-new.mm line:7542
void *objc_destructInstance(id obj) 
{
    if (obj) {
        // Read all of the flags at once for performance.
        // 是否有C++析构函数
        bool cxx = obj->hasCxxDtor();
        // 是否有关联对象
        bool assoc = obj->hasAssociatedObjects();

        // This order is important.
        // C++对象销毁处理
        if (cxx) object_cxxDestruct(obj);
        // 移除关联对象处理
        if (assoc) _object_remove_assocations(obj);
        // 引用计数处理、移除弱引用对象处理
        obj->clearDeallocating();
    }

    return obj;
}