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

源码:
inline voidobjc_object::rootDealloc(){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);}}idobject_dispose(id obj){if (!obj) return nil;objc_destructInstance(obj);free(obj);return nil;}
c++ 析构函数 & 移除关联对象
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);obj->clearDeallocating();}return obj;}
处理对象在散列表中的引用计数 & 弱引用表
inline voidobjc_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());}
voidobjc_object::sidetable_clearDeallocating(){SideTable& table = SideTables()[this];// clear any weak table items// clear extra retain count and deallocating bit// (fixme warn or abort if extra retain count == 0 ?)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();}
NEVER_INLINE voidobjc_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) {//注意:传参与上面方法的 it 不同,这个是 this,也会释放掉散列表中额外存储的引用计数// 引用计数如果满了,会分一半放到散列表中存储table.refcnts.erase(this);}table.unlock();}
