理解iOS weak對象釋放后置為nil原理
1逸吵、弱引用對象釋放的瀏覽與普通對象釋放流程基本一樣损肛,區(qū)別在于清除散列表厢破。
1)清除散列表入口方法
sidetable_clearDeallocating
void objc_object::sidetable_clearDeallocating()
{
SideTable& table = SideTables()[this];
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();
}
這里在散列表中找到當(dāng)想對象的位置it
,接著在弱引用表中刪除弱引用對象
治拿,最后在散列表中清除it
位置的數(shù)據(jù)摩泪;
2)
weak_clear_no_lock
方法分享
void weak_clear_no_lock(weak_table_t *weak_table, id referent_id)
{
objc_object *referent = (objc_object *)referent_id;
weak_entry_t *entry = weak_entry_for_referent(weak_table, referent);
if (entry == nil) {
return;
}
weak_referrer_t *referrers;
size_t count;
if (entry->out_of_line()) {
referrers = entry->referrers;
count = TABLE_SIZE(entry);
}
else {
referrers = entry->inline_referrers;
count = WEAK_INLINE_COUNT;
}
for (size_t i = 0; i < count; ++i) {
objc_object **referrer = referrers[i];
if (referrer) {
if (*referrer == referent) {
*referrer = nil;
}
else if (*referrer) {
_objc_inform("__weak variable at %p holds %p instead of %p. "
"This is probably incorrect use of "
"objc_storeWeak() and objc_loadWeak(). "
"Break on objc_weak_error to debug.\n",
referrer, (void*)*referrer, (void*)referent);
objc_weak_error();
}
}
}
weak_entry_remove(weak_table, entry);
}
首先根據(jù)weak_entry_for_referent(weak_table, referent)
對象在弱引用表中找到實(shí)體entry
,取出實(shí)體中弱引用數(shù)組referrers
劫谅。referrers
存儲的是弱引用指針地址加勤,循環(huán)數(shù)組置空,最后在弱引用表中移除實(shí)體weak_entry_remove(weak_table, entry)
同波。