释放对象的流程:

    • 小对象不处理内存
    • 是否包含弱引用、关联对象、c++析构函数、外挂散列表
      • 没有,则直接free
      • 有则先释放这些,再free
        • 关联对象
        • c++析构函数
        • 弱引用表
        • 引用计数

    image.png
    源码:

    1. inline void
    2. objc_object::rootDealloc()
    3. {
    4. if (isTaggedPointer()) return; // fixme necessary?
    5. if (fastpath(isa.nonpointer &&
    6. !isa.weakly_referenced &&
    7. !isa.has_assoc &&
    8. !isa.has_cxx_dtor &&
    9. !isa.has_sidetable_rc))
    10. {
    11. assert(!sidetable_present());
    12. free(this);
    13. }
    14. else {
    15. object_dispose((id)this);
    16. }
    17. }
    18. id
    19. object_dispose(id obj)
    20. {
    21. if (!obj) return nil;
    22. objc_destructInstance(obj);
    23. free(obj);
    24. return nil;
    25. }

    c++ 析构函数 & 移除关联对象

    1. void *objc_destructInstance(id obj)
    2. {
    3. if (obj) {
    4. // Read all of the flags at once for performance.
    5. bool cxx = obj->hasCxxDtor();
    6. bool assoc = obj->hasAssociatedObjects();
    7. // This order is important.
    8. if (cxx) object_cxxDestruct(obj);
    9. if (assoc) _object_remove_assocations(obj);
    10. obj->clearDeallocating();
    11. }
    12. return obj;
    13. }

    处理对象在散列表中的引用计数 & 弱引用表

    1. inline void
    2. objc_object::clearDeallocating()
    3. {
    4. if (slowpath(!isa.nonpointer)) {
    5. // Slow path for raw pointer isa.
    6. sidetable_clearDeallocating();
    7. }
    8. else if (slowpath(isa.weakly_referenced || isa.has_sidetable_rc)) {
    9. // Slow path for non-pointer isa with weak refs and/or side table data.
    10. clearDeallocating_slow();
    11. }
    12. assert(!sidetable_present());
    13. }
    1. void
    2. objc_object::sidetable_clearDeallocating()
    3. {
    4. SideTable& table = SideTables()[this];
    5. // clear any weak table items
    6. // clear extra retain count and deallocating bit
    7. // (fixme warn or abort if extra retain count == 0 ?)
    8. table.lock();
    9. RefcountMap::iterator it = table.refcnts.find(this);
    10. if (it != table.refcnts.end()) {
    11. if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) {
    12. weak_clear_no_lock(&table.weak_table, (id)this);
    13. }
    14. table.refcnts.erase(it);
    15. }
    16. table.unlock();
    17. }
    1. NEVER_INLINE void
    2. objc_object::clearDeallocating_slow()
    3. {
    4. ASSERT(isa.nonpointer && (isa.weakly_referenced || isa.has_sidetable_rc));
    5. SideTable& table = SideTables()[this];
    6. table.lock();
    7. if (isa.weakly_referenced) {
    8. weak_clear_no_lock(&table.weak_table, (id)this);
    9. }
    10. if (isa.has_sidetable_rc) {
    11. //注意:传参与上面方法的 it 不同,这个是 this,也会释放掉散列表中额外存储的引用计数
    12. // 引用计数如果满了,会分一半放到散列表中存储
    13. table.refcnts.erase(this);
    14. }
    15. table.unlock();
    16. }