__block可以用于解決block內(nèi)部無法修改auto變量值的問題
__block不能修飾全局變量谣妻、靜態(tài)變量(static)
編譯器會將__block變量包裝成一個對象
__block int age = 18;
^{
NSLog(@"%d", age);
}();
struct __main_block_impl_0 {
struct __block_impl impl;
struct __main_block_desc_0* Desc;
__Block_byref_age_0 *age;// by ref
};
struct __Block_byref_age_0 {
void *__isa;
__Block_byref_age_0 *__forwarding;
int __flags;
int size;
int age;
};
-
__block的內(nèi)存管理
當(dāng)block在棧上時,并不會對__block變量產(chǎn)生強引用
-
當(dāng)block被copy到堆時
會調(diào)用block內(nèi)部的copy函數(shù)
copy函數(shù)內(nèi)部會調(diào)用_Block_object_assign函數(shù)
_Block_object_assign函數(shù)會對__block變量形成強引用(retain)
-
當(dāng)block從堆中移除時
會調(diào)用block內(nèi)部的dispose函數(shù)
dispose函數(shù)內(nèi)部會調(diào)用_Block_object_dispose函數(shù)
_Block_object_dispose函數(shù)會自動釋放引用的__block變量(release)
-
__block的__forwarding指針
-
對象類型的auto變量、__block變量
當(dāng)block在棧上時,對它們都不會產(chǎn)生強引用
當(dāng)block拷貝到堆上時赂苗,都會通過copy函數(shù)來處理它們
__block變量(假設(shè)變量名叫做a)
_Block_object_assign((void*)&dst->a, (void*)src->a, 8/*BLOCK_FIELD_IS_BYREF*/);
對象類型的auto變量(假設(shè)變量名叫做p)
_Block_object_assign((void*)&dst->p, (void*)src->p, 3/*BLOCK_FIELD_IS_OBJECT*/);
- 當(dāng)block從堆上移除時清女,都會通過dispose函數(shù)來釋放它們
__block變量(假設(shè)變量名叫做a)
_Block_object_dispose((void*)src->a, 8/*BLOCK_FIELD_IS_BYREF*/);
對象類型的auto變量(假設(shè)變量名叫做p)
_Block_object_dispose((void*)src->p, 3/*BLOCK_FIELD_IS_OBJECT*/);
-
被__block修飾的對象類型
當(dāng)__block變量在棧上時,不會對指向的對象產(chǎn)生強引用
當(dāng)__block變量被copy到堆時
會調(diào)用__block變量內(nèi)部的copy函數(shù)
copy函數(shù)內(nèi)部會調(diào)用_Block_object_assign函數(shù)
_Block_object_assign函數(shù)會根據(jù)所指向?qū)ο蟮男揎椃╛_strong租悄、__weak、__unsafe_unretained)做出相應(yīng)的操作恩袱,形成強引用(retain)或者弱引用(注意:這里僅限于ARC時會retain泣棋,MRC時不會retain)如果__block變量從堆上移除
會調(diào)用__block變量內(nèi)部的dispose函數(shù)
dispose函數(shù)內(nèi)部會調(diào)用_Block_object_dispose函數(shù)
_Block_object_dispose函數(shù)會自動釋放指向的對象(release)-
循環(huán)引用問題
- 解決方案(ARC):
用__weak
、__unsafe_unretained
解決
用__block
解決(必須要調(diào)用block) - 解決方案(MRC):
用__unsafe_unretained
解決
用__block
解決