本人簡書地址iOS中Block實現原理的全面分析html
void blockTest()
{
void (^block)(void) = ^{
NSLog(@"Hello World!");
};
block();
}
int main(int argc, char * argv[]) {
@autoreleasepool {
blockTest();
}
}
複製代碼
經過clang命令查看編譯器是如何實現Block的,在終端輸入clang -rewrite-objc main.m
,而後會在當前目錄生成main.cpp
的C++文件,代碼以下:c++
struct __blockTest_block_impl_0 {
struct __block_impl impl;
struct __blockTest_block_desc_0* Desc;
__blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, int flags=0) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
static void __blockTest_block_func_0(struct __blockTest_block_impl_0 *__cself) {
NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_0048d2_mi_0);
}
static struct __blockTest_block_desc_0 {
size_t reserved;
size_t Block_size;
} __blockTest_block_desc_0_DATA = { 0, sizeof(struct __blockTest_block_impl_0)};
void blockTest() {
void (*block)(void) = ((void (*)())&__blockTest_block_impl_0((void *)__blockTest_block_func_0, &__blockTest_block_desc_0_DATA));
((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
}
int main(int argc, char * argv[]) {
/* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;
blockTest();
}
}
static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 };
複製代碼
下面咱們一個一個來看macos
struct __blockTest_block_impl_0 {
struct __block_impl impl;
struct __blockTest_block_desc_0* Desc;
__blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, int flags=0) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
複製代碼
__blockTest_block_impl_0
是Block
的C++實現,是一個結構體,從命名能夠看出表示blockTest
中的第一個(0
)Block
。一般包含兩個成員變量__block_impl impl
,__blockTest_block_desc_0* Desc
和一個構造函數。bash
struct __block_impl {
void *isa;
int Flags;
int Reserved;
void *FuncPtr;
};
複製代碼
__block_impl也是一個結構體app
Block
執行時調用的函數,也就是Block
須要執行的代碼塊。在本例中是__blockTest_block_func_0
函數。static struct __blockTest_block_desc_0 {
size_t reserved;
size_t Block_size;
} __blockTest_block_desc_0_DATA = { 0, sizeof(struct __blockTest_block_impl_0)};
複製代碼
__blockTest_block_desc_0
是一個結構體,包含兩個成員變量:函數
Block
版本升級所需的預留區空間,在這裏爲0。Block
大小(sizeof(struct __blockTest_block_impl_0))
。__blockTest_block_desc_0_DATA
是一個__blockTest_block_desc_0
的一個實例。post
__blockTest_block_func_0
就是Block
的執行時調用的函數,參數是一個__blockTest_block_impl_0
類型的指針。學習
static void __blockTest_block_func_0(struct __blockTest_block_impl_0 *__cself) {
NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_0048d2_mi_0);
}
複製代碼
void blockTest() {
void (*block)(void) = ((void (*)())&__blockTest_block_impl_0((void *)__blockTest_block_func_0, &__blockTest_block_desc_0_DATA));
((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
}
複製代碼
第一部分,定義Blockui
void (*block)(void) = ((void (*)())&__blockTest_block_impl_0((void *)__blockTest_block_func_0, &__blockTest_block_desc_0_DATA));
複製代碼
咱們看到block
變成了一個指針,指向一個經過__blockTest_block_impl_0
構造函數實例化的結構體__blockTest_block_impl_0
實例,__blockTest_block_impl_0
在初始化的時候須要兩個個參數:atom
__blockTest_block_func_0
:Block
塊的函數指針。__blockTest_block_desc_0_DATA
:做爲靜態全局變量初始化__main_block_desc_0
的結構體實例指針。第二部分,調用Block
((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
複製代碼
((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)
經過block->FuncPtr
指針找到__blockTest_block_func_0
函數而且轉成(void (*)(__block_impl *))
類型。
((__block_impl *)block)
而後將block
做爲參數傳給這個函數調用。
在__block_impl
中咱們看到Flags
,如今來詳細講一講。
在這裏Block_private.h能夠看到Flags
的具體信息:
// Values for Block_layout->flags to describe block objects
enum {
BLOCK_DEALLOCATING = (0x0001), // runtime
BLOCK_REFCOUNT_MASK = (0xfffe), // runtime
BLOCK_NEEDS_FREE = (1 << 24), // runtime
BLOCK_HAS_COPY_DISPOSE = (1 << 25), // compiler
BLOCK_HAS_CTOR = (1 << 26), // compiler: helpers have C++ code
BLOCK_IS_GC = (1 << 27), // runtime
BLOCK_IS_GLOBAL = (1 << 28), // compiler
BLOCK_USE_STRET = (1 << 29), // compiler: undefined if !BLOCK_HAS_SIGNATURE
BLOCK_HAS_SIGNATURE = (1 << 30), // compiler
BLOCK_HAS_EXTENDED_LAYOUT=(1 << 31) // compiler
};
複製代碼
引用淺談 block(1) - clang 改寫後的 block 結構的解釋:
也就是說,通常狀況下,一個
block
的 flags 成員默認設置爲 0。若是當block
須要Block_copy()
和Block_release
這類拷貝輔助函數,則會設置成1 << 25
,也就是BLOCK_HAS_COPY_DISPOSE
類型。能夠搜索到大量講述Block_copy
方法的博文,其中涉及到了BLOCK_HAS_COPY_DISPOSE
。
總結一下枚舉類的用法,前 16 位即起到標記做用,又可記錄引用計數:
- BLOCK_DEALLOCATING:釋放標記。通常經常使用 BLOCK_NEEDS_FREE 作 位與 操做,一同傳入 Flags ,告知該 block 可釋放。
咱們看到直接在block
修改變量會提示錯誤,爲何呢?
void blockTest()
{
int num = 10;
void (^block)(void) = ^{
NSLog(@"%d",num);
};
num = 20;
block();
}
int main(int argc, char * argv[]) {
@autoreleasepool {
blockTest();
}
}
複製代碼
打印結果是10,clang改寫後的代碼以下:
struct __blockTest_block_impl_0 {
struct __block_impl impl;
struct __blockTest_block_desc_0* Desc;
int num;
__blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, int _num, int flags=0) : num(_num) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
static void __blockTest_block_func_0(struct __blockTest_block_impl_0 *__cself) {
int num = __cself->num; // bound by copy
NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_3c2714_mi_0,num);
}
void blockTest() {
int num = 10;
void (*block)(void) = ((void (*)())&__blockTest_block_impl_0((void *)__blockTest_block_func_0, &__blockTest_block_desc_0_DATA, num));
num = 20;
((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
}
複製代碼
__blockTest_block_impl_0
多了一個成員變量int num;
,再看看構造函數__blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, int _num, int flags=0)
,能夠看到第三個參數只是變量的值,這也就解釋了爲何打印的是10,由於**block
截獲的是值**。
void blockTest()
{
static int num = 10;
void (^block)(void) = ^{
NSLog(@"%d",num);
num = 30;
};
num = 20;
block();
NSLog(@"%d",num);
}
複製代碼
能夠在block
內部修改變量了,同時打印結果是20,30。clang改寫後的代碼以下:
struct __blockTest_block_impl_0 {
struct __block_impl impl;
struct __blockTest_block_desc_0* Desc;
int *num;
__blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, int *_num, int flags=0) : num(_num) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
static void __blockTest_block_func_0(struct __blockTest_block_impl_0 *__cself) {
int *num = __cself->num; // bound by copy
NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_5a95f6_mi_0,(*num));
(*num) = 30;
}
void blockTest() {
static int num = 10;
void (*block)(void) = ((void (*)())&__blockTest_block_impl_0((void *)__blockTest_block_func_0, &__blockTest_block_desc_0_DATA, &num));
num = 20;
NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_5a95f6_mi_1,num);
((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
}
複製代碼
__blockTest_block_impl_0
多了一個成員變量int *num;
,和上面不一樣的是,此次**block
截獲的是指針**,因此能夠在內部經過指針修改變量的值,同時在外部修改變量的值,block
也能"感知到"。那麼爲何以前傳遞指針呢?由於變量是棧上,做用域是函數blockTest
內,那麼有可能變量比block
先銷燬,這時候block
再經過指針去訪問變量就會有問題。而static
修飾的變量不會被銷燬,也就不用擔憂。
int num = 10;
void blockTest()
{
void (^block)(void) = ^{
NSLog(@"%d",num);
num = 30;
};
num = 20;
block();
NSLog(@"%d",num);
}
複製代碼
打印結果是20,30。clang改寫後的代碼以下:
int num = 10;
struct __blockTest_block_impl_0 {
struct __block_impl impl;
struct __blockTest_block_desc_0* Desc;
__blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, int flags=0) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
static void __blockTest_block_func_0(struct __blockTest_block_impl_0 *__cself) {
NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_1875c6_mi_0,num);
num = 30;
}
複製代碼
很是簡單,在初始化__blockTest_block_impl_0
並無把num
做爲參數,__blockTest_block_func_0
中也是直接訪問全局變量。
總結:
變量類型 | 是否捕獲到block內部 | 訪問方式 |
---|---|---|
局部auto變量 | 是 | 值傳遞 |
局部static變量 | 是 | 指針傳遞 |
全局變量 | 否 | 直接訪問 |
void blockTest()
{
__block int num = 10;
void (^block)(void) = ^{
NSLog(@"%d",num);
num = 30;
};
num = 20;
block();
NSLog(@"%d",num);
}
複製代碼
效果和使用static修飾變量同樣,clang改寫後的代碼以下:
struct __Block_byref_num_0 {
void *__isa;
__Block_byref_num_0 *__forwarding;
int __flags;
int __size;
int num;
};
struct __blockTest_block_impl_0 {
struct __block_impl impl;
struct __blockTest_block_desc_0* Desc;
__Block_byref_num_0 *num; // by ref
__blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, __Block_byref_num_0 *_num, int flags=0) : num(_num->__forwarding) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
static void __blockTest_block_func_0(struct __blockTest_block_impl_0 *__cself) {
__Block_byref_num_0 *num = __cself->num; // bound by ref
NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_018b76_mi_0,(num->__forwarding->num));
(num->__forwarding->num) = 30;
}
static void __blockTest_block_copy_0(struct __blockTest_block_impl_0*dst, struct __blockTest_block_impl_0*src) {_Block_object_assign((void*)&dst->num, (void*)src->num, 8/*BLOCK_FIELD_IS_BYREF*/);}
static void __blockTest_block_dispose_0(struct __blockTest_block_impl_0*src) {_Block_object_dispose((void*)src->num, 8/*BLOCK_FIELD_IS_BYREF*/);}
static struct __blockTest_block_desc_0 {
size_t reserved;
size_t Block_size;
void (*copy)(struct __blockTest_block_impl_0*, struct __blockTest_block_impl_0*);
void (*dispose)(struct __blockTest_block_impl_0*);
} __blockTest_block_desc_0_DATA = { 0, sizeof(struct __blockTest_block_impl_0), __blockTest_block_copy_0, __blockTest_block_dispose_0};
void blockTest() {
__attribute__((__blocks__(byref))) __Block_byref_num_0 num = {(void*)0,(__Block_byref_num_0 *)&num, 0, sizeof(__Block_byref_num_0), 10};
void (*block)(void) = ((void (*)())&__blockTest_block_impl_0((void *)__blockTest_block_func_0, &__blockTest_block_desc_0_DATA, (__Block_byref_num_0 *)&num, 570425344));
(num.__forwarding->num) = 20;
((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_018b76_mi_1,(num.__forwarding->num));
}
複製代碼
哇,難受啊兄dei,怎麼多出來這麼多東西,不要緊,慢慢分析。
__blockTest_block_impl_0
多出來一個成員變量__Block_byref_num_0 *num;
,咱們看到通過__block
修飾的變量類型變成告終構體__Block_byref_num_0
,__blockTest_block_impl_0
多出來一個成員變量__Block_byref_num_0 *num;
,block
捕獲的是__Block_byref_num_0
類型指針,
__Block_byref_num_0
咱們看到__Block_byref_num_0
是一個結構體,而且有一個isa
,所以咱們能夠知道它其實就是一個對象。同時還有一個__Block_byref_a_0 *
類型的__forwarding
和num
,num
咱們能猜到就是用來保存變量的值,__forwarding
就有一點複雜了,後面慢慢講。
__blockTest_block_copy_0和**__blockTest_block_dispose_0**
__blockTest_block_copy_0
中調用的是_Block_object_assign
,__blockTest_block_dispose_0
中調用的是_Block_object_dispose
。
函數 | 調用時機 |
---|---|
__blockTest_block_copy_0 | __block 變量結構體實例從棧拷貝到堆時 |
__blockTest_block_dispose_0 | __block 變量結構體實例引用計數爲0時 |
關於_Block_object_assign
和_Block_object_dispose
更詳細代碼能夠在runtime.c 中查看。
BLOCK_FIELD_IS_BYREF
咱們看到_Block_object_assign
和_Block_object_dispose
中都有個參數值爲8,BLOCK_FIELD_IS_BYREF
類型,什麼意思呢?在Block_private.h 中能夠查看到:
// Runtime support functions used by compiler when generating copy/dispose helpers
// Values for _Block_object_assign() and _Block_object_dispose() parameters
enum {
// see function implementation for a more complete description of these fields and combinations
BLOCK_FIELD_IS_OBJECT = 3, // id, NSObject, __attribute__((NSObject)), block, ...
BLOCK_FIELD_IS_BLOCK = 7, // a block variable
BLOCK_FIELD_IS_BYREF = 8, // the on stack structure holding the __block variable
BLOCK_FIELD_IS_WEAK = 16, // declared __weak, only used in byref copy helpers
BLOCK_BYREF_CALLER = 128, // called from __block (byref) copy/dispose support routines.
};
複製代碼
BLOCK_FIELD_IS_OBJECT
:OC對象類型BLOCK_FIELD_IS_BLOCK
:是一個blockBLOCK_FIELD_IS_BYREF
:在棧上被__block
修飾的變量BLOCK_FIELD_IS_WEAK
:被__weak
修飾的變量,只在Block_byref
管理內部對象內存時使用BLOCK_BYREF_CALLER
:處理Block_byref
內部對象內存的時候會加的一個額外標記(告訴內部實現不要進行retain或者copy)__blockTest_block_desc_0 咱們能夠看到它多了兩個回調函數指針*copy
和*dispose
,這兩個指針會被賦值爲__main_block_copy_0
和__main_block_dispose_0
最後咱們看到訪問num
是這樣的:
__Block_byref_num_0 *num = __cself->num; // bound by ref
(num->__forwarding->num) = 30;
複製代碼
下面就講一講爲何要這樣。
在前面咱們講到__block_impl
指向的_NSConcreteStackBlock類型的類對象,其實總共有三種類型:
類型 | 存儲區域 |
---|---|
_NSConcreteStackBlock | 棧 |
_NSConcreteGlobalBlock | 數據區 |
_NSConcreteMallocBlock | 堆 |
前面也講到copy
和dispose
,在ARC環境下,有哪些狀況編譯器會自動將棧上的把Block
從棧上覆制到堆上呢?
Block從棧中複製到堆 |
---|
調用Block的copy實例方法時 |
Block做爲函數返回值返回時 |
在帶有usingBlock的Cocoa方法或者GCD的API中傳遞Block時候 |
將block賦給帶有__strong修飾符的id類型或者Block類型時 |
當Bock
從棧中複製到堆,__block
也跟着變化:
Block
在棧上時,__block
的存儲域是棧,__block
變量被棧上的Block
持有。Block
被複制到堆上時,會經過調用Block
內部的copy
函數,copy函數內部會調用_Block_object_assign
函數。此時__block
變量的存儲域是堆,__block
變量被堆上的Block
持有。Block
被釋放,會調用Block
內部的dispose
,dispose
函數內部會調用_Block_object_dispose
,堆上的__block
被釋放。Block
使用棧上的__block
變量,__block
變量被棧上的多個Block
持有。Block0
被複制到堆上時,__block
也會被複制到堆上,被堆上Block0
持有。Block1
仍然持有棧上的__block
,原棧上__block
變量的__forwarding
指向拷貝到堆上以後的__block
變量。Block1
也被複制到堆上時,堆上的__block
被堆上的Block0
和Block1
只有,而且__block
的引用計數+1。Block
都被釋放,__block
變量結構體實例引用計數爲0,調用_Block_object_dispose
,堆上的__block
被釋放。下圖是描述__forwarding
變化。這也就能解釋__forwarding
存在的意義:
__forwarding 保證在棧上或者堆上都能正確訪問對應變量
int main(int argc, char * argv[]) {
int num = 10;
NSLog(@"%@",[^{
NSLog(@"%d",num);
} class]);
void (^block)(void) = ^{
NSLog(@"%d",num);
};
NSLog(@"%@",[block class]);
}
複製代碼
打印結果:
2019-05-04 18:40:48.470228+0800 BlockTest[35824:16939613] __NSStackBlock__
2019-05-04 18:40:48.470912+0800 BlockTest[35824:16939613] __NSMallocBlock__
複製代碼
咱們能夠看到第一個Block
沒有賦值給__strong
指針,而第二個Block
沒有賦值給__strong
指針,因此第一個在棧上,而第二個在堆上。
int main(int argc, char * argv[]) {
{
Person *person = [[Person alloc] init];
person.name = @"roy";
NSLog(@"%@",[^{
NSLog(@"%@",person.name);
} class]);
NSLog(@"%@",@"+++++++++++++");
}
NSLog(@"%@",@"------------");
}
複製代碼
打印結果:
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@end
@implementation Person
- (void)dealloc {
NSLog(@"-------dealloc-------");
}
@end
typedef void(^Block)(void);
int main(int argc, char * argv[]) {
{
Person *person = [[Person alloc] init];
person.name = @"roy";
NSLog(@"%@",[^{
NSLog(@"%@",person.name);
} class]);
NSLog(@"%@",@"+++++++++++++");
}
NSLog(@"%@",@"------------");
}
複製代碼
咱們看到當Block
內部訪問了對象類型的auto對象時,若是Block
是在棧上,將不會對auto對象產生強引用。
typedef void(^Block)(void);
int main(int argc, char * argv[]) {
Block block;
{
Person *person = [[Person alloc] init];
person.name = @"roy";
block = ^{
NSLog(@"%@",person.name);
};
person.name = @"david";
NSLog(@"%@",@"+++++++++++++");
}
NSLog(@"%@",@"------------");
block ();
}
複製代碼
打印結果是
2019-05-04 17:46:27.083280+0800 BlockTest[33745:16864251] +++++++++++++
2019-05-04 17:46:27.083934+0800 BlockTest[33745:16864251] ------------
2019-05-04 17:46:27.084018+0800 BlockTest[33745:16864251] david
2019-05-04 17:46:27.084158+0800 BlockTest[33745:16864251] -------dealloc-------
複製代碼
咱們看到是先打印的david
再調用Person
的析構方法dealloc
,在終端輸入clang -rewrite-objc -fobjc-arc -fobjc-runtime=macosx-10.13 main.m -fobjc-arc
,clang在ARC環境下改寫後的代碼以下:
struct __main_block_impl_0 {
struct __block_impl impl;
struct __main_block_desc_0* Desc;
Person *__strong person;
__main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, Person *__strong _person, int flags=0) : person(_person) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
複製代碼
咱們看到__main_block_impl_0
中的Person *__strong person;
成員變量。
Block
截獲了auto對象,當Block
被拷貝到堆上,Block
強引用auto對象,這就能解釋了爲何超出了person
的做用域,person
沒有當即釋放,當Block
釋放以後,會自動去掉對該對象的強引用,該對象就會被釋放了。
typedef void(^Block)(void);
int main(int argc, char * argv[]) {
Block block;
{
Person *person = [[Person alloc] init];
person.name = @"roy";
__weak Person *weakPerson = person;
block = ^{
NSLog(@"%@",weakPerson.name);
};
weakPerson.name = @"david";
NSLog(@"%@",@"+++++++++++++");
}
NSLog(@"%@",@"------------");
block ();
}
複製代碼
打印結果是
2019-05-04 17:49:38.858554+0800 BlockTest[33856:16869229] +++++++++++++
2019-05-04 17:49:38.859218+0800 BlockTest[33856:16869229] -------dealloc-------
2019-05-04 17:49:38.859321+0800 BlockTest[33856:16869229] ------------
2019-05-04 17:49:38.859403+0800 BlockTest[33856:16869229] (null)
複製代碼
直接在終端輸入clang -rewrite-objc main.m
會報cannot create __weak reference because the current deployment target does not support weak ref
錯誤。須要用clang -rewrite-objc -fobjc-arc -fobjc-runtime=macosx-10.13 main.m
,-fobjc-arc
表明當前是ARC環境 -fobjc-runtime=macosx-10.13
:表明當前運行時環境,缺一不可,clang以後的代碼:
struct __main_block_impl_0 {
struct __block_impl impl;
struct __main_block_desc_0* Desc;
Person *__weak weakPerson;
__main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, Person *__weak _weakPerson, int flags=0) : weakPerson(_weakPerson) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
複製代碼
咱們看到__main_block_impl_0
中的Person *__weak weakPerson;
成員變量。
總結:
Block
內部訪問了對象類型的auto對象時,若是Block
是在棧上,將不會對auto對象產生強引用。Block
內部的copy函數,copy函數內部會調用_Block_object_assign
函數,_Block_object_assign
會根據auto對象的修飾符(__strong
,__weak
,__unsafe_unretained
)作出相應的操做,當使用的是__strong
時,將會對person
對象的引用計數加1,當爲__weak
時,引用計數不變。Block
從對上移除,會調用block內部的dispose
函數,內部會調用_Block_object_dispose
函數,這個函數會自動釋放引用的auto
對象。@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, copy) void (^block)(void);
- (void)testReferenceSelf;
@end
@implementation Person
- (void)testReferenceSelf {
self.block = ^ {
NSLog(@"self.name = %s", self.name.UTF8String);
};
self.block();
}
- (void)dealloc {
NSLog(@"-------dealloc-------");
}
@end
int main(int argc, char * argv[]) {
Person *person = [[Person alloc] init];
person.name = @"roy";
[person testReferenceSelf];
}
複製代碼
打印結果是self.name = roy
,Person
的析構方法dealloc
並無執行,這是典型的循環引用,下面咱們研究研究爲啥會循環引用。clang改寫後的代碼以下:
struct __Person__testReferenceSelf_block_impl_0 {
struct __block_impl impl;
struct __Person__testReferenceSelf_block_desc_0* Desc;
Person *const __strong self;
__Person__testReferenceSelf_block_impl_0(void *fp, struct __Person__testReferenceSelf_block_desc_0 *desc, Person *const __strong _self, int flags=0) : self(_self) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
static void _I_Person_testReferenceSelf(Person * self, SEL _cmd) {
((void (*)(id, SEL, void (*)()))(void *)objc_msgSend)((id)self, sel_registerName("setBlock:"), ((void (*)())&__Person__testReferenceSelf_block_impl_0((void *)__Person__testReferenceSelf_block_func_0, &__Person__testReferenceSelf_block_desc_0_DATA, self, 570425344)));
((void (*(*)(id, SEL))())(void *)objc_msgSend)((id)self, sel_registerName("block"))();
}
複製代碼
咱們看到原本Person中testReferenceSelf
方法是沒有參數的,可是轉成C++以後多出來兩個參數:* self
和_cmd
,再看看__Person__testReferenceSelf_block_impl_0
中多出來一個成員變量Person *const __strong self;
,所以咱們知道Person中block
捕獲了self
,block
強引用self
,同時self
也強引用block
,所以造成循環引用。
@implementation Person
- (void)testReferenceSelf {
__weak typeof(self) weakself = self;
self.block = ^ {
__strong typeof(self) strongself = weakself;
NSLog(@"self.name = %s", strongself.name.UTF8String);
};
self.block();
}
- (void)dealloc {
NSLog(@"-------dealloc-------");
}
@end
複製代碼
打印結果:
2019-05-04 19:27:48.274358+0800 BlockTest[37426:17007507] self.name = roy
2019-05-04 19:27:48.275016+0800 BlockTest[37426:17007507] -------dealloc-------
複製代碼
咱們看到Person對象被正常釋放了,說明不存在循環引用,爲何呢?clang改寫後的代碼以下:
struct __Person__testReferenceSelf_block_impl_0 {
struct __block_impl impl;
struct __Person__testReferenceSelf_block_desc_0* Desc;
Person *const __weak weakself;
__Person__testReferenceSelf_block_impl_0(void *fp, struct __Person__testReferenceSelf_block_desc_0 *desc, Person *const __weak _weakself, int flags=0) : weakself(_weakself) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
static void _I_Person_testReferenceSelf(Person * self, SEL _cmd) {
__attribute__((objc_ownership(weak))) typeof(self) weakself = self;
((void (*)(id, SEL, void (*)()))(void *)objc_msgSend)((id)self, sel_registerName("setBlock:"), ((void (*)())&__Person__testReferenceSelf_block_impl_0((void *)__Person__testReferenceSelf_block_func_0, &__Person__testReferenceSelf_block_desc_0_DATA, weakself, 570425344)));
((void (*(*)(id, SEL))())(void *)objc_msgSend)((id)self, sel_registerName("block"))();
}
複製代碼
能夠看到__Person__testReferenceSelf_block_impl_0
結構體中weakself成員是一個__weak
修飾的Person類型對象,也就是說__Person__testReferenceSelf_block_impl_0
對Person的依賴是弱依賴。weak修飾變量是在runtime中進行處理的,在Person對象的Dealloc方法中會調用weak引用的處理方法,從weak_table中尋找弱引用的依賴對象,進行清除處理。
好了,關於Block就寫到這裏了,花了五一的三天時間解決了一個基礎知識點,如釋重負,寫的真心累。
參考文章
淺談 block(1) - clang 改寫後的 block 結構
Objc Block實現分析
(四)Block之 __block修飾符及其存儲域
(三)Block之截獲變量和對象 關於Block再囉嗦幾句
__block變量存儲域
Block學習⑤--block對對象變量的捕獲
淺談Block實現原理及內存特性之三: copy過程分析
iOS底層原理總結 - 探尋block的本質(一)