@[TOC](iOS arc weak指針原理)
ARC 都幫我們做了什么?
是 LLVM 和 runTime 系統(tǒng)相互協(xié)作的一個(gè)結(jié)果,
LLVM 編繹器幫我們補(bǔ)個(gè) [obj release] 蜡饵,[obj retain]等引用增減方法。
下面將通過分析蘋果官方源碼:蘋果官方objc4_723源碼下載
weak是什么?
- weak表其實(shí)是一個(gè)hash(哈希)表鬓梅,Key是所指對(duì)象的地址,Value是weak指針的地址數(shù)組谨湘。更多人的人只是知道weak是弱引用绽快,所引用對(duì)象的計(jì)數(shù)器不會(huì)加一,并在引用對(duì)象被釋放的時(shí)候自動(dòng)被設(shè)置為nil紧阔。通常用于解決循環(huán)引用問題坊罢。但現(xiàn)在單知道這些已經(jīng)不足以應(yīng)對(duì)面試了,好多公司會(huì)問weak的原理擅耽。
weak是怎么實(shí)現(xiàn)的活孩?
1. weak原理簡介
Runtime維護(hù)了一個(gè)weak表,用于存儲(chǔ)指向某個(gè)對(duì)象的所有weak指針乖仇。weak表其實(shí)是一個(gè)hash(哈希)表憾儒,Key是所指對(duì)象的地址询兴,Value是weak指針的地址(這個(gè)地址的值是所指對(duì)象的地址)數(shù)組。
weak 的實(shí)現(xiàn)原理可以概括一下三步:
1起趾、初始化時(shí):runtime會(huì)調(diào)用objc_initWeak函數(shù)诗舰,初始化一個(gè)新的weak指針指向?qū)ο蟮牡刂贰?/p>
2、添加引用時(shí):objc_initWeak函數(shù)會(huì)調(diào)用 objc_storeWeak() 函數(shù)训裆, objc_storeWeak() 的作用是更新指針指向眶根,創(chuàng)建對(duì)應(yīng)的弱引用表。
3缭保、釋放時(shí)汛闸,調(diào)用clearDeallocating函數(shù)。clearDeallocating函數(shù)首先根據(jù)對(duì)象地址獲取所有weak指針地址的數(shù)組艺骂,然后遍歷這個(gè)數(shù)組把其中的數(shù)據(jù)設(shè)為nil诸老,最后把這個(gè)entry從weak表中刪除,最后清理對(duì)象的記錄钳恕。
2. weak簡單測(cè)試
關(guān)于對(duì)象的三個(gè)修飾詞__strong别伏、__weak、__unsafe_unretained忧额,測(cè)試結(jié)果分別用“01__strong指針引用對(duì)象.png”厘肮、“02__weak指針引用對(duì)象.png”、“03__unsafe_unretained指針引用對(duì)象.png”三張圖表示睦番。
- 測(cè)試代碼
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
__strong ZYClass *strongZYClass;
__weak ZYClass *weakZYClass;
__unsafe_unretained ZYClass *unsafeZYClass;
#pragma clang diagnostic pop
NSLog(@"test begin");
{
ZYClass *zyClass = [[ZYClass alloc] init];
strongZYClass = zyClass;
// weakZYClass = zyClass;
// unsafeZYClass = zyClass;
}
NSLog(@"test over%@",strongZYClass);
}
測(cè)試結(jié)果:
-
01__strong指針引用對(duì)象
01__strong指針引用對(duì)象 -
02__weak指針引用對(duì)象
02__weak指針引用對(duì)象 -
03__unsafe_unretained指針引用對(duì)象
03__unsafe_unretained指針引用對(duì)象
"zyClass"定義的作用域如下:
{
ZYClass *zyClass = [[ZYClass alloc] init];
strongZYClass = zyClass;
// weakZYClass = zyClass;
// unsafeZYClass = zyClass;
}
鑒于__strong指針對(duì)對(duì)象有強(qiáng)引用關(guān)系类茂,所以"zyClass"在出作用域后并沒有立即銷毀;
__weak指針對(duì)對(duì)象是弱引用關(guān)系托嚣,不持有引用對(duì)象巩检。所以"zyClass"在出作用域后就銷毀了;
__unsafe_unretained指針對(duì)對(duì)象是弱引用關(guān)系示启,不持有引用對(duì)象兢哭。所以"zyClass"在出作用域后就銷毀了。(與__weak不同的是夫嗓,__weak引用的對(duì)象銷毀后迟螺,系統(tǒng)會(huì)將對(duì)象置為nil,而__unsafe_unretained不這么做舍咖,導(dǎo)致EXC_BAD_ACCESS錯(cuò)誤矩父。)
3. weak原理分析
3.1 weak指針幫我們干了啥?
程序運(yùn)行時(shí)將弱引用存到一個(gè)哈希表中,當(dāng)對(duì)象obj要銷毀的時(shí)候排霉,哈希函數(shù)根據(jù)obj地址獲取到索引窍株,然后從哈希表中取出obj對(duì)應(yīng)的弱引用集合weak_entries,遍歷weak_entries并一一清空
分析objc 源碼:
當(dāng)一個(gè)對(duì)象釋放的時(shí)候,會(huì)執(zhí)行"- (void)dealloc {}"方法夹姥,在objc源碼的“NSObject.mm”中找到了該函數(shù)以及相關(guān)調(diào)用流程
// Replaced by NSZombies
- (void)dealloc {
_objc_rootDealloc(self);
}
void _objc_rootDealloc(id obj)
{
assert(obj);
obj->rootDealloc();
}
inline void objc_object::rootDealloc()
{
if (isTaggedPointer()) return; // fixme necessary?
/* nonpointer 0 代表普通的指針 0,代表普通的指針辙诞,存儲(chǔ)著Class辙售、Meta-Class對(duì)象的內(nèi)存地址
1,代表優(yōu)化過飞涂,使用位域存儲(chǔ)更多的信息
has_assoc 是否有關(guān)聯(lián)對(duì)象 如果沒有釋放會(huì)很快
has_cxx_dtor 是否有C++析構(gòu)函數(shù) 如果沒有釋放會(huì)更快
weakly_referenced 釋放有被弱引用指向 如果沒有 釋放會(huì)更快
has_sidetable_rc 引用計(jì)數(shù)器是否過大無法存儲(chǔ)在isa中
如果為1旦部,那么引用計(jì)數(shù)會(huì)存儲(chǔ)在一個(gè)叫SideTable的類的屬性中
*/
/// 快速釋放對(duì)象 滿足上邊的條件
if (fastpath(isa.nonpointer &&
!isa.weakly_referenced &&
!isa.has_assoc &&
!isa.has_cxx_dtor &&
!isa.has_sidetable_rc))
{
assert(!sidetable_present());
free(this);
}
else {///不能夠快速是否 需要進(jìn)一步做釋放處理
object_dispose((id)this);
}
}
id object_dispose(id obj)
{
if (!obj) return nil;
/// 釋放對(duì)象前 要將對(duì)象的關(guān)聯(lián)屬性 weak 指針置空 修改引用計(jì)數(shù) isa 指針的一些信息
objc_destructInstance(obj);
free(obj);
return nil;
}
/***********************************************************************
* 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.
/// 是否有C++析構(gòu)函數(shù)
bool cxx = obj->hasCxxDtor();
/// 是否有關(guān)聯(lián)屬性
bool assoc = obj->hasAssociatedObjects();
// This order is important.
//清除對(duì)象的成員變量
if (cxx) object_cxxDestruct(obj);
//清除對(duì)象的關(guān)聯(lián)對(duì)象
if (assoc) _object_remove_assocations(obj);
///明確回收
obj->clearDeallocating();
}
return obj;
}
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());
}
// Slow path of clearDeallocating()
// for objects with nonpointer isa
// that were ever weakly referenced
// or whose retain count ever overflowed to the side table.
NEVER_INLINE void objc_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) {
table.refcnts.erase(this);
}
table.unlock();///解鎖
}
/**
* Called by dealloc; nils out all weak pointers that point to the
* provided object so that they can no longer be used.
*
* @param weak_table
* @param referent The object being deallocated.
*/
void weak_clear_no_lock(weak_table_t *weak_table, id referent_id)
{
///當(dāng)前對(duì)象強(qiáng)轉(zhuǎn)為 objc_object 結(jié)構(gòu)體指針類型
objc_object *referent = (objc_object *)referent_id;
///獲weak散列表中跟當(dāng)前對(duì)象對(duì)應(yīng)的 weak_entry_t *結(jié)構(gòu)體指針
weak_entry_t *entry = weak_entry_for_referent(weak_table, referent);
if (entry == nil) {///如果為 nil 代表 沒有查找到這個(gè)對(duì)象在 weak 表里存放 可能是這個(gè)對(duì)象轉(zhuǎn)成CF對(duì)象 并轉(zhuǎn)移了對(duì)象引用計(jì)數(shù)所有權(quán)
/// XXX shouldn't happen, but does with mismatched CF/objc
//printf("XXX no entry for clear deallocating %p\n", referent);
return;
}
// zero out references
// 存放所有 weak 指針數(shù)組
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];
///weak 指針數(shù)組中的元素 是 當(dāng)前對(duì)象指向的指針地址 將指針置空 nil
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 表中移除跟當(dāng)前對(duì)象weak_entry_t有關(guān)的內(nèi)容
weak_entry_remove(weak_table, entry);
}
/**weak_entry_for_referent(weak_table_t *weak_table, objc_object *referent) 根據(jù)當(dāng)前對(duì)象指針作為查找條件從
weak_table_t 中獲取 weak_entry_t * 指針類型結(jié)構(gòu)體
這里邊是一個(gè)簡單的 hash 算法 用對(duì)象內(nèi)存地址轉(zhuǎn)成一個(gè) hash 值
然后 & weak_table->mask 獲得一個(gè)開始索引 然后根據(jù)這個(gè)索引在數(shù)組里查找元素 ,
如果生成的索引查找的元素不是我們想要的 ,
可以用 index + 1 & weak_table->mask 重新生成一個(gè) index ,
直到算出一個(gè)合適的索引 ,然后從數(shù)組里 取出 一個(gè) weak_entry_t * 結(jié)構(gòu)體指針
*/
/**
* Return the weak reference table entry for the given referent.
* If there is no entry for referent, return NULL.
* Performs a lookup.
*
* @param weak_table
* @param referent The object. Must not be nil.
*
* @return The table of weak referrers to this object.
*/
static weak_entry_t * weak_entry_for_referent(weak_table_t *weak_table, objc_object *referent)
{
assert(referent);
weak_entry_t *weak_entries = weak_table->weak_entries;
if (!weak_entries) return nil;
///用對(duì)象內(nèi)存地址轉(zhuǎn)成一個(gè) hash 值 然后 & weak_table->mask 獲得一個(gè)開始索引
size_t begin = hash_pointer(referent) & weak_table->mask;
size_t index = begin;
size_t hash_displacement = 0;
///直到 index 對(duì)應(yīng)的 weak_entries[index].referent == referent 是我們要釋放掉的對(duì)象時(shí) 才會(huì)退出循環(huán)
while (weak_table->weak_entries[index].referent != referent) {
/// 用 index + 1 方式 生成一個(gè)新的 index 繼續(xù)在 weak_entries查找
index = (index+1) & weak_table->mask;
if (index == begin) bad_weak_table(weak_table->weak_entries);
hash_displacement++;
if (hash_displacement > weak_table->max_hash_displacement) {
return nil;
}
}
///根據(jù)計(jì)算出來的 index 取出一個(gè)weak_entry_t * 結(jié)構(gòu)體指針
return &weak_table->weak_entries[index];
}
- 函數(shù)inline void objc_object::rootDealloc()中有一句判斷if (isTaggedPointer()) return; // fixme necessary?,這個(gè)地方條件成立就會(huì)return ,而不會(huì)釋放對(duì)象较店,為什么士八?
實(shí)際上蘋果在64位系統(tǒng)開始推出了“Tagged Pointer”技術(shù)來優(yōu)化NSNumber、NSString梁呈、NSDate等小對(duì)象的存儲(chǔ)婚度,在沒有引入“Tagged Pointer”技術(shù)之前,NSNumber等對(duì)象需要?jiǎng)討B(tài)分配內(nèi)存官卡、維護(hù)引用技術(shù)蝗茁,NSNumber指針存儲(chǔ)的是NSNumber對(duì)象的地址值。iOS引入“Tagged Pointer”技術(shù)之后寻咒,NSNumber指針里面存儲(chǔ)的數(shù)據(jù)變成了“Tag+Data”,也就是直接將數(shù)據(jù)存儲(chǔ)在指針中哮翘。僅當(dāng)指針不夠存儲(chǔ)數(shù)據(jù)時(shí),才會(huì)使用動(dòng)態(tài)分配內(nèi)存的方式來存儲(chǔ)數(shù)據(jù)毛秘。
“Tagged Pointer”的好處是:一方面節(jié)約計(jì)算機(jī)內(nèi)存饭寺,另一方面因?yàn)榭梢灾苯訌闹羔樦凶x取數(shù)據(jù),可以節(jié)約之前objc_msgSend流程消耗的時(shí)間叫挟。
那對(duì)于下面三個(gè)“對(duì)象”(這里注意“”修飾艰匙,因?yàn)閍、b本質(zhì)上屬于Tagged Pointer類型霞揉,而不是OC對(duì)象):
a. NSNumber *number1 = @4;
b. NSNumber number2 = @5;
c. NSNumber number3 = @(0xFFFFFFFFFFFFFFF)旬薯。
對(duì)于a、b适秩,所對(duì)應(yīng)的二級(jí)制編碼分別為0b0100绊序、0b0101,僅僅占用3 bit,用一個(gè)字節(jié)(8bit)就足夠存儲(chǔ)了秽荞,而OC的指針number1骤公、number2都占用8個(gè)字節(jié),因此我們完全可以將a扬跋、b的值存放在指針中阶捆,那么a、b實(shí)際上就不是真正的對(duì)象了,也就不存在執(zhí)行所謂的- (void) dealloc{}流程洒试。如果按照64位之前的策略倍奢,那存儲(chǔ)a、b這樣的小對(duì)象垒棋,需要在堆空間alloc init出一個(gè)NSNumber對(duì)象卒煞,然后將@10放入對(duì)象中,這個(gè)過程至少占用16字節(jié)叼架,然后在棧區(qū)用一個(gè)指針指向這個(gè)NSNumber對(duì)象畔裕,棧空間指針又占用8字節(jié)乖订,所以至少需要24字節(jié)存儲(chǔ)a扮饶、b這樣的小對(duì)象,很浪費(fèi)內(nèi)存乍构。
- 分析代碼得到甜无,當(dāng)一個(gè)對(duì)象被回收的時(shí)候調(diào)用流程:
- -(void)dealloc ->
- _objc_rootDealloc(id obj) ->
- objc_object::rootDealloc() ->
- object_dispose(id obj) ->
- objc_destructInstance(id obj) ->
- objc_object::clearDeallocating() ->
- objc_object::clearDeallocating_slow() ->
- weak_clear_no_lock(weak_table_t weak_table, id referent_id) ->
- weak_entry_for_referent(weak_table_t *weak_table, objc_object *referent)
再看一次"weak_entry_t * weak_entry_for_referent(weak_table_t *weak_table, objc_object *referent)"函數(shù)實(shí)現(xiàn)細(xì)節(jié)
///直到 index 對(duì)應(yīng)的 weak_entries[index].referent == referent 是我們要釋放掉的對(duì)象時(shí) 才會(huì)退出循環(huán)
while (weak_table->weak_entries[index].referent != referent) {
/// 用 index + 1 方式 生成一個(gè)新的 index 繼續(xù)在 weak_entries查找
index = (index+1) & weak_table->mask;
if (index == begin) bad_weak_table(weak_table->weak_entries);
hash_displacement++;
if (hash_displacement > weak_table->max_hash_displacement) {
return nil;
}
}
函數(shù)內(nèi)部利用正在被dealloc的對(duì)象地址referent 通過哈希函數(shù)hash_pointer()計(jì)算,再&weak_table->mask獲得begin索引蜡吧,所以可推測(cè)weak_table是一個(gè)散列表結(jié)構(gòu)毫蚓,weak_table來自于SideTable對(duì)象中的“weak_table”成員,有了這個(gè)當(dāng)前對(duì)象在散列表中的索引昔善,就可以通過索引獲取當(dāng)前對(duì)象的弱引用數(shù)組了(當(dāng)然根據(jù)獲取到的begin索引得到的散列結(jié)果可能并不是這個(gè)“dealloc對(duì)象”的元潘,因?yàn)榇嬖谏⒘袥_突箫攀,所以這里面有while ()循環(huán)判斷當(dāng)前index散列值的“ referent”與我們傳入的“ referent”是否匹配)川尖。
通過這個(gè)while循環(huán),可見這個(gè)散列表解決散列沖突采用的是“開放尋址法”江咳。
程序運(yùn)行時(shí)將弱引用存到一個(gè)哈希表中返咱,當(dāng)對(duì)象obj要銷毀的時(shí)候钥庇,哈希函數(shù)根據(jù)obj地址獲取到索引,然后從哈希表中取出obj對(duì)應(yīng)的弱引用集合weak_entries咖摹,遍歷weak_entries并一一清空(也就對(duì)應(yīng)源碼中函數(shù)void weak_clear_no_lock(weak_table_t weak_table, id referent_id)所做的referrer = nil;)评姨。
3.2 weak實(shí)現(xiàn)的流程
3.2.1 初始化時(shí):runtime會(huì)調(diào)用objc_initWeak函數(shù),objc_initWeak函數(shù)會(huì)初始化一個(gè)新的weak指針指向?qū)ο蟮牡刂贰?/h6>
{
NSObject *obj = [[NSObject alloc] init];
id __weak obj1 = obj;
}
{
NSObject *obj = [[NSObject alloc] init];
id __weak obj1 = obj;
}
當(dāng)我們初始化一個(gè)weak變量時(shí)萤晴,runtime會(huì)調(diào)用 NSObject.mm 中的objc_initWeak函數(shù)吐句。這個(gè)函數(shù)在Clang中的聲明如下:
id objc_initWeak(id *object, id value);
而對(duì)于 objc_initWeak() 方法的實(shí)現(xiàn)
id objc_initWeak(id *location, id newObj) {
// 查看對(duì)象實(shí)例是否有效
// 無效對(duì)象直接導(dǎo)致指針釋放
if (!newObj) {
*location = nil;
return nil;
}
// 這里傳遞了三個(gè) bool 數(shù)值
// 使用 template 進(jìn)行常量參數(shù)傳遞是為了優(yōu)化性能
return storeWeakfalse/*old*/, true/*new*/, true/*crash*/>
(location, (objc_object*)newObj);
}
可以看出,這個(gè)函數(shù)僅僅是一個(gè)深層函數(shù)的調(diào)用入口店读,而一般的入口函數(shù)中嗦枢,都會(huì)做一些簡單的判斷(例如 objc_msgSend 中的緩存判斷),這里判斷了其指針指向的類對(duì)象是否有效屯断,無效直接釋放文虏,不再往深層調(diào)用函數(shù)侣诺。否則,object將被注冊(cè)為一個(gè)指向value的__weak對(duì)象氧秘。而這事應(yīng)該是objc_storeWeak函數(shù)干的年鸳。
注意:objc_initWeak函數(shù)有一個(gè)前提條件:就是object必須是一個(gè)沒有被注冊(cè)為__weak對(duì)象的有效指針。而value則可以是null丸相,或者指向一個(gè)有效的對(duì)象阻星。
3.2.2 添加引用時(shí):objc_initWeak函數(shù)會(huì)調(diào)用 objc_storeWeak() 函數(shù), objc_storeWeak() 的作用是更新指針指向已添,創(chuàng)建對(duì)應(yīng)的弱引用表。
- objc_storeWeak的函數(shù)聲明如下:
id objc_storeWeak(id *location, id value);
- objc_storeWeak() 的具體實(shí)現(xiàn)如下:
// HaveOld: true - 變量有值
// false - 需要被及時(shí)清理滥酥,當(dāng)前值可能為 nil
// HaveNew: true - 需要被分配的新值更舞,當(dāng)前值可能為 nil
// false - 不需要分配新值
// CrashIfDeallocating: true - 說明 newObj 已經(jīng)釋放或者 newObj 不支持弱引用,該過程需要暫停
// false - 用 nil 替代存儲(chǔ)
template bool HaveOld, bool HaveNew, bool CrashIfDeallocating>
static id storeWeak(id *location, objc_object *newObj) {
// 該過程用來更新弱引用指針的指向
// 初始化 previouslyInitializedClass 指針
Class previouslyInitializedClass = nil;
id oldObj;
// 聲明兩個(gè) SideTable
// ① 新舊散列創(chuàng)建
SideTable *oldTable;
SideTable *newTable;
// 獲得新值和舊值的鎖存位置(用地址作為唯一標(biāo)示)
// 通過地址來建立索引標(biāo)志坎吻,防止桶重復(fù)
// 下面指向的操作會(huì)改變舊值
retry:
if (HaveOld) {
// 更改指針缆蝉,獲得以 oldObj 為索引所存儲(chǔ)的值地址
oldObj = *location;
oldTable = &SideTables()[oldObj];
} else {
oldTable = nil;
}
if (HaveNew) {
// 更改新值指針,獲得以 newObj 為索引所存儲(chǔ)的值地址
newTable = &SideTables()[newObj];
} else {
newTable = nil;
}
// 加鎖操作瘦真,防止多線程中競(jìng)爭(zhēng)沖突
SideTable::lockTwoHaveOld, HaveNew>(oldTable, newTable);
// 避免線程沖突重處理
// location 應(yīng)該與 oldObj 保持一致刊头,如果不同,說明當(dāng)前的 location 已經(jīng)處理過 oldObj 可是又被其他線程所修改
if (HaveOld && *location != oldObj) {
SideTable::unlockTwoHaveOld, HaveNew>(oldTable, newTable);
goto retry;
}
// 防止弱引用間死鎖
// 并且通過 +initialize 初始化構(gòu)造器保證所有弱引用的 isa 非空指向
if (HaveNew && newObj) {
// 獲得新對(duì)象的 isa 指針
Class cls = newObj->getIsa();
// 判斷 isa 非空且已經(jīng)初始化
if (cls != previouslyInitializedClass &&
!((objc_class *)cls)->isInitialized()) {
// 解鎖
SideTable::unlockTwoHaveOld, HaveNew>(oldTable, newTable);
// 對(duì)其 isa 指針進(jìn)行初始化
_class_initialize(_class_getNonMetaClass(cls, (id)newObj));
// 如果該類已經(jīng)完成執(zhí)行 +initialize 方法是最理想情況
// 如果該類 +initialize 在線程中
// 例如 +initialize 正在調(diào)用 storeWeak 方法
// 需要手動(dòng)對(duì)其增加保護(hù)策略诸尽,并設(shè)置 previouslyInitializedClass 指針進(jìn)行標(biāo)記
previouslyInitializedClass = cls;
// 重新嘗試
goto retry;
}
}
// ② 清除舊值
if (HaveOld) {
weak_unregister_no_lock(&oldTable->weak_table, oldObj, location);
}
// ③ 分配新值
if (HaveNew) {
newObj = (objc_object *)weak_register_no_lock(&newTable->weak_table,
(id)newObj, location,
CrashIfDeallocating);
// 如果弱引用被釋放 weak_register_no_lock 方法返回 nil
// 在引用計(jì)數(shù)表中設(shè)置若引用標(biāo)記位
if (newObj && !newObj->isTaggedPointer()) {
// 弱引用位初始化操作
// 引用計(jì)數(shù)那張散列表的weak引用對(duì)象的引用計(jì)數(shù)中標(biāo)識(shí)為weak引用
newObj->setWeaklyReferenced_nolock();
}
// 之前不要設(shè)置 location 對(duì)象原杂,這里需要更改指針指向
*location = (id)newObj;
}
else {
// 沒有新值,則無需更改
}
SideTable::unlockTwoHaveOld, HaveNew>(oldTable, newTable);
return (id)newObj;
}
- 撇開源碼中各種鎖操作您机,來看看這段代碼都做了些什么穿肄。
- SideTable
SideTable 這個(gè)結(jié)構(gòu)體,我給他起名引用計(jì)數(shù)和弱引用依賴表际看,因?yàn)樗饕糜诠芾韺?duì)象的引用計(jì)數(shù)和 weak 表咸产。在 NSObject.mm 中聲明其數(shù)據(jù)結(jié)構(gòu):
struct SideTable {
// 保證原子操作的自旋鎖
spinlock_t slock;
// 引用計(jì)數(shù)的 hash 表
RefcountMap refcnts;
// weak 散列表 所有 weak 指針存放在這個(gè)表里,weak 引用全局 hash 表
weak_table_t weak_table;
}
對(duì)于 slock 和 refcnts 兩個(gè)成員不用多說仲闽,第一個(gè)是為了防止競(jìng)爭(zhēng)選擇的自旋鎖脑溢,第二個(gè)是協(xié)助對(duì)象的 isa 指針的 extra_rc 共同引用計(jì)數(shù)的變量(對(duì)于對(duì)象結(jié)果,在今后的文中提到)赖欣。這里主要看 weak 全局 hash 表的結(jié)構(gòu)與作用屑彻。
- weak表
weak表是一個(gè)弱引用表,實(shí)現(xiàn)為一個(gè)weak_table_t結(jié)構(gòu)體畏鼓,存儲(chǔ)了某個(gè)對(duì)象相關(guān)的的所有的弱引用信息酱酬。其定義如下(具體定義在objc-weak.h中):
struct weak_table_t {
// 指針數(shù)組 存放 weak_entry_t 類型,保存了所有指向指定對(duì)象的 weak 指針
weak_entry_t *weak_entries;
// 存儲(chǔ)空間云矫,散列表最大可存放內(nèi)容容量
size_t num_entries;
// 參與判斷引用計(jì)數(shù)輔助量膳沽,&mask 可以獲取一個(gè) key 從而在散列表快速查找某個(gè)元素
uintptr_t mask;
// hash key 最大偏移值
uintptr_t max_hash_displacement;
};
這是一個(gè)全局弱引用hash表。使用不定類型對(duì)象的地址作為 key ,用 weak_entry_t 類型結(jié)構(gòu)體對(duì)象作為 value 挑社。其中的 weak_entries 成員陨界,從字面意思上看,即為弱引用表入口痛阻。其實(shí)現(xiàn)也是這樣的菌瘪。
其中weak_entry_t是存儲(chǔ)在弱引用表中的一個(gè)內(nèi)部結(jié)構(gòu)體,它負(fù)責(zé)維護(hù)和存儲(chǔ)指向一個(gè)對(duì)象的所有弱引用hash表阱当。其定義如下:
typedef objc_object ** weak_referrer_t;
struct weak_entry_t {
DisguisedPtrobjc_object> referent;
union {
struct {
weak_referrer_t *referrers;
uintptr_t out_of_line : 1;
uintptr_t num_refs : PTR_MINUS_1;
uintptr_t mask;
uintptr_t max_hash_displacement;
};
struct {
// out_of_line=0 is LSB of one of these (don't care which)
weak_referrer_t inline_referrers[WEAK_INLINE_COUNT];
};
}
}
在 weak_entry_t 的結(jié)構(gòu)中俏扩,DisguisedPtr referent 是對(duì)泛型對(duì)象的指針做了一個(gè)封裝,通過這個(gè)泛型類來解決內(nèi)存泄漏的問題弊添。從注釋中寫 out_of_line 成員為最低有效位录淡,當(dāng)其為0的時(shí)候, weak_referrer_t 成員將擴(kuò)展為多行靜態(tài) hash table油坝。其實(shí)其中的 weak_referrer_t 是二維 objc_object 的別名嫉戚,通過一個(gè)二維指針地址偏移,用下標(biāo)作為 hash 的 key澈圈,做成了一個(gè)弱引用散列彬檀。
那么在有效位未生效的時(shí)候,out_of_line 瞬女、 num_refs窍帝、 mask 、 max_hash_displacement 有什么作用诽偷?
//out_of_line:最低有效位盯桦,也是標(biāo)志位。當(dāng)標(biāo)志位 0 時(shí)渤刃,增加引用表指針緯度拥峦。
//num_refs:引用數(shù)值。這里記錄弱引用表中引用有效數(shù)字卖子,因?yàn)槿跻帽硎褂玫氖庆o態(tài) hash 結(jié)構(gòu)略号,所以需要使用變量來記錄數(shù)目。
//mask:計(jì)數(shù)輔助量洋闽。
//max_hash_displacement:hash 元素上限閥值玄柠。
其實(shí) out_of_line 的值通常情況下是等于零的,所以弱引用表總是一個(gè) objc_objective 指針二維數(shù)組诫舅。一維 objc_objective 指針可構(gòu)成一張弱引用散列表羽利,通過第三緯度實(shí)現(xiàn)了多張散列表,并且表數(shù)量為 WEAK_INLINE_COUNT 刊懈。
總結(jié)一下 StripedMap[] :
StripedMap 是一個(gè)模板類这弧,在這個(gè)類中有一個(gè) array 成員娃闲,用來存儲(chǔ) PaddedT 對(duì)象,并且其中對(duì)于 [] 符的重載定義中匾浪,會(huì)返回這個(gè) PaddedT 的 value 成員皇帮,這個(gè) value 就是我們傳入的 T 泛型成員,也就是 SideTable 對(duì)象蛋辈。在 array 的下標(biāo)中属拾,這里使用了 indexForPointer 方法通過位運(yùn)算計(jì)算下標(biāo),實(shí)現(xiàn)了靜態(tài)的 Hash Table冷溶。而在 weak_table 中渐白,其成員 weak_entry 會(huì)將傳入對(duì)象的地址加以封裝起來,并且其中也有訪問全局弱引用表的入口逞频。
舊對(duì)象解除注冊(cè)操作 weak_unregister_no_lock
該方法主要作用是將舊對(duì)象在 weak_table 中接觸 weak 指針的對(duì)應(yīng)綁定礼预。根據(jù)函數(shù)名,稱之為解除注冊(cè)操作虏劲。從源碼中,可以知道其功能就是從 weak_table 中接觸 weak 指針的綁定褒颈。而其中的遍歷查詢柒巫,就是針對(duì)于 weak_entry 中的多張弱引用散列表。
新對(duì)象添加注冊(cè)操作 weak_register_no_lock
這一步與上一步相反谷丸,通過 weak_register_no_lock 函數(shù)把心的對(duì)象進(jìn)行注冊(cè)操作堡掏,完成與對(duì)應(yīng)的弱引用表進(jìn)行綁定操作。
初始化弱引用對(duì)象流程一覽
弱引用的初始化刨疼,從上文的分析中可以看出泉唁,主要的操作部分就在弱引用表的取鍵、查詢散列揩慕、創(chuàng)建弱引用表等操作亭畜,可以總結(jié)出如下的流程圖:
這個(gè)圖中省略了很多情況的判斷,但是當(dāng)聲明一個(gè) weak 會(huì)調(diào)用上圖中的這些方法迎卤。當(dāng)然拴鸵, storeWeak 方法不僅僅用在 weak 的聲明中,在 class 內(nèi)部的操作中也會(huì)常常通過該方法來對(duì) weak 對(duì)象進(jìn)行操作蜗搔。
3.2.3 釋放時(shí)劲藐,調(diào)用clearDeallocating函數(shù)。clearDeallocating函數(shù)首先根據(jù)對(duì)象地址獲取所有weak指針地址的數(shù)組樟凄,然后遍歷這個(gè)數(shù)組把其中的數(shù)據(jù)設(shè)為nil聘芜,最后把這個(gè)entry從weak表中刪除,最后清理對(duì)象的記錄缝龄。
- 當(dāng)weak引用指向的對(duì)象被釋放時(shí)汰现,又是如何去處理weak指針的呢挂谍?當(dāng)釋放對(duì)象時(shí),其基本流程如下:
(1) 調(diào)用objc_release
(2) 因?yàn)閷?duì)象的引用計(jì)數(shù)為0服鹅,所以執(zhí)行dealloc
(3) 在dealloc中凳兵,調(diào)用了_objc_rootDealloc函數(shù)
(4) 在_objc_rootDealloc中,調(diào)用了object_dispose函數(shù)
(5) 調(diào)用objc_destructInstance
(6) 最后調(diào)用objc_clear_deallocating
- 調(diào)用objc_release
- 因?yàn)閷?duì)象的引用計(jì)數(shù)為0企软,所以執(zhí)行dealloc
- 在dealloc中庐扫,調(diào)用了_objc_rootDealloc函數(shù)
- 在_objc_rootDealloc中,調(diào)用了object_dispose函數(shù)
- 調(diào)用objc_destructInstance
- 最后調(diào)用objc_clear_deallocating
objc_clear_deallocating函數(shù)實(shí)現(xiàn):
void objc_clear_deallocating(id obj)
{
assert(obj);
assert(!UseGC);
if (obj->isTaggedPointer()) return;
obj->clearDeallocating();
}
也就是調(diào)用了clearDeallocating仗哨,繼續(xù)追蹤可以發(fā)現(xiàn)形庭,它最終是使用了迭代器來取weak表的value,然后調(diào)用weak_clear_no_lock,然后查找對(duì)應(yīng)的value厌漂,將該weak指針置空萨醒,weak_clear_no_lock函數(shù)的實(shí)現(xiàn)如下:
/**
* Called by dealloc; nils out all weak pointers that point to the
* provided object so that they can no longer be used.
*
* @param weak_table
* @param referent The object being deallocated.
*/
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) {
/// XXX shouldn't happen, but does with mismatched CF/objc
//printf("XXX no entry for clear deallocating %p\n", referent);
return;
}
// zero out references
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);
}
objc_clear_deallocating該函數(shù)的動(dòng)作如下:
1、從weak表中獲取廢棄對(duì)象的地址為鍵值的記錄
2苇倡、將包含在記錄中的所有附有 weak修飾符變量的地址富纸,賦值為nil
3、將weak表中該記錄刪除
4旨椒、從引用計(jì)數(shù)表中刪除廢棄對(duì)象的地址為鍵值的記錄