转载自:
block没那么难(一):block的实现
block没那么难(二):block和变量的内存管理
block没那么难(三):block和对象的内存管理
本系列博文总结自《Pro Multithreading and Memory Management for iOS and OS X with ARC》
block 顾名思义就是代码块,将同一逻辑的代码放在一个块,使代码更简洁紧凑,易于阅读,而且它比函数使用更方便,代码更美观,因而广受开发者欢迎。但同时 block 也是 iOS 开发中坑最多的地方之一,因此有必要了解下 block 的实现原理,知其然,更知其所以然,才能从根本上避免挖坑和踩坑。
需要知道的是,block 只是 Objective-C 对闭包的实现,并不是 iOS 独有的概念,在 C++、Java 等语言也有实现闭包,名称不同而已。
特别声明
以下研究所用的过程代码由 clang 编译前端生成,仅作理解之用。实际上 clang 根本不会将 block 转换成人类可读的代码,它对 block 到底做了什么,谁也不知道。
所以,切勿将过程代码当做block的实际实现,切记切记!!!
将下面的 test.m
代码用 clang 工具翻译 test.cpp
代码
clang -rewrite-objc test.m
test.m 代码
/************* Objective-C 源码 *************/
int main()
{
void (^blk)(void) = ^{ printf("Block\n"); };`
blk();
return 0;
}
test.cpp
/************* 使用 clang 翻译后如下 *************/
struct __block_impl
{
void *isa;
int Flags;
int Reserved;
void *FuncPtr;
};
struct __main_block_impl_0
{
struct __block_impl impl;
struct __main_block_desc_0* Desc;
__main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int flags=0)
{
impl.isa = &_NSConcreteStackBlock
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
25. `static void __main_block_func_0(struct __main_block_impl_0 *__cself)`
26. `{`
27. `printf("Block\n");`
28. `}`
30. `static struct __main_block_desc_0`
31. `{`
32. `size_t reserved;`
33. `size_t Block_size;`
34. `} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0) };`
36. `int main()`
37. `{`
38. `void (*blk)(void) = (void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA);`
40. `((void (*)(__block_impl *))((__block_impl *)blk)->FuncPtr)((__block_impl *)blk);`
42. `return 0;`
43. `}`
接着,我们逐一来看下这些函数和结构体
block 结构体信息详解
struct __block_impl
<pre class="prettyprint linenums prettyprinted" data-anchor-id="bgxy" style="padding: 9.5px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 14px; color: rgb(51, 51, 51); border-radius: 4px; display: block; margin: 0px 0px 20px; line-height: 20px; word-break: break-all; overflow-wrap: break-word; white-space: pre-wrap; background: none 0px 0px repeat scroll rgba(102, 128, 153, 0.05); border: 0px solid rgba(0, 0, 0, 0.15); box-shadow: rgba(255, 255, 255, 0.1) 0px 1px 2px inset, rgba(102, 128, 153, 0.05) 45px 0px 0px inset, rgba(102, 128, 153, 0.05) 0px 1px 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
// __block_impl 是 block 实现的结构体
struct __block_impl
{
void *isa;
int Flags;
int Reserved;
void *FuncPtr;
};
</pre>
-
isa
指向实例对象,表明 block 本身也是一个 Objective-C 对象。block 的三种类型:_NSConcreteStackBlock
、_NSConcreteGlobalBlock
、_NSConcreteMallocBlock
,即当代码执行时,isa 有三种值impl.isa = &_NSConcreteStackBlock;
impl.isa = &_NSConcreteMallocBlock;
impl.isa = &_NSConcreteGlobalBlock; Flags
按位承载 block 的附加信息;Reserved
保留变量;FuncPtr
函数指针,指向 Block 要执行的函数,即{ printf("Block\n") }
;
struct __main_block_impl_0
<pre class="prettyprint linenums prettyprinted" data-anchor-id="h3ae" style="padding: 9.5px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 14px; color: rgb(51, 51, 51); border-radius: 4px; display: block; margin: 0px 0px 20px; line-height: 20px; word-break: break-all; overflow-wrap: break-word; white-space: pre-wrap; background: none 0px 0px repeat scroll rgba(102, 128, 153, 0.05); border: 0px solid rgba(0, 0, 0, 0.15); box-shadow: rgba(255, 255, 255, 0.1) 0px 1px 2px inset, rgba(102, 128, 153, 0.05) 45px 0px 0px inset, rgba(102, 128, 153, 0.05) 0px 1px 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
// __main_block_impl_0 是 block 实现的结构体,也是 block 实现的入口
struct __main_block_impl_0
{
struct __block_impl impl;
struct __main_block_desc_0* Desc;
__main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int flags=0)
{
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
</pre>
impl
block 实现的结构体变量,该结构体前面已说明;Desc
描述 block 的结构体变量;__main_block_impl_0
结构体的构造函数,初始化结构体变量impl
、Desc
;
static void __main_block_func_0
<pre class="prettyprint linenums prettyprinted" data-anchor-id="5e8h" style="padding: 9.5px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 14px; color: rgb(51, 51, 51); border-radius: 4px; display: block; margin: 0px 0px 20px; line-height: 20px; word-break: break-all; overflow-wrap: break-word; white-space: pre-wrap; background: none 0px 0px repeat scroll rgba(102, 128, 153, 0.05); border: 0px solid rgba(0, 0, 0, 0.15); box-shadow: rgba(255, 255, 255, 0.1) 0px 1px 2px inset, rgba(102, 128, 153, 0.05) 45px 0px 0px inset, rgba(102, 128, 153, 0.05) 0px 1px 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
// __main_block_func_0 是 block 要最终要执行的函数代码
static void __main_block_func_0(struct __main_block_impl_0 *__cself)
{
printf("Block\n");
}
</pre>
static struct __main_block_desc_0
<pre class="prettyprint linenums prettyprinted" data-anchor-id="ns3i" style="padding: 9.5px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 14px; color: rgb(51, 51, 51); border-radius: 4px; display: block; margin: 0px 0px 20px; line-height: 20px; word-break: break-all; overflow-wrap: break-word; white-space: pre-wrap; background: none 0px 0px repeat scroll rgba(102, 128, 153, 0.05); border: 0px solid rgba(0, 0, 0, 0.15); box-shadow: rgba(255, 255, 255, 0.1) 0px 1px 2px inset, rgba(102, 128, 153, 0.05) 45px 0px 0px inset, rgba(102, 128, 153, 0.05) 0px 1px 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
// __main_block_desc_0 是 block 的描述信息结构体
static struct __main_block_desc_0
{
size_t reserved;
size_t Block_size;
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0) };
</pre>
reserved
结构体信息保留字段Block_size
结构体大小
此处已定义了一个该结构体类型的变量 __main_block_desc_0_DATA
block 实现的执行流程
<svg height="458.65625" version="1.1" width="559.296875" xmlns="http://www.w3.org/2000/svg" style="overflow: hidden; position: relative;"><text x="10" y="18.328125" text-anchor="start" font="10px "Arial"" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-style: normal; font-variant: normal; font-weight: normal; font-stretch: normal; font-size: 15px; line-height: normal; font-family: Arial;" id="startt" class="flowchartt" font-size="15px" transform="matrix(1,0,0,1,249.3984,12.9219)"><tspan dy="5.171875" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">main()</tspan></text><text x="10" y="27.25" text-anchor="start" font="10px "Arial"" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-style: normal; font-variant: normal; font-weight: normal; font-stretch: normal; font-size: 15px; line-height: normal; font-family: Arial;" id="op1t" class="flowchartt" font-size="15px" transform="matrix(1,0,0,1,4,103.5781)"><tspan dy="-3.75" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">调用 __main_block_impl_0 构造函数初始化结构体</tspan><tspan dy="18" x="10" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">__main_block_impl_0(__main_block_func_0 , __main_block_desc_0_DATA);</tspan></text><text x="10" y="18.25" text-anchor="start" font="10px "Arial"" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-style: normal; font-variant: normal; font-weight: normal; font-stretch: normal; font-size: 15px; line-height: normal; font-family: Arial;" id="op2t" class="flowchartt" font-size="15px" transform="matrix(1,0,0,1,109.3516,221.0781)"><tspan dy="5.25" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">得到的__main_block_impl_0 类型变量赋值给 blk</tspan></text><text x="10" y="18.328125" text-anchor="start" font="10px "Arial"" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-style: normal; font-variant: normal; font-weight: normal; font-stretch: normal; font-size: 15px; line-height: normal; font-family: Arial;" id="op3t" class="flowchartt" font-size="15px" transform="matrix(1,0,0,1,120.0938,320.5)"><tspan dy="5.171875" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">执行 blk->FuncPtr()函数,即 printf("Block\n");</tspan></text><text x="10" y="18.25" text-anchor="start" font="10px "Arial"" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-style: normal; font-variant: normal; font-weight: normal; font-stretch: normal; font-size: 15px; line-height: normal; font-family: Arial;" id="endt" class="flowchartt" font-size="15px" transform="matrix(1,0,0,1,257.3047,420.1563)"><tspan dy="5.25" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">End</tspan></text></svg>
最基础的 block 实现就这么简单。
接着再看 block 获取外部变量
block 获取外部变量
运行下面的代码
<pre class="prettyprint linenums prettyprinted" data-anchor-id="nxzm" style="padding: 9.5px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 14px; color: rgb(51, 51, 51); border-radius: 4px; display: block; margin: 0px 0px 20px; line-height: 20px; word-break: break-all; overflow-wrap: break-word; white-space: pre-wrap; background: none 0px 0px repeat scroll rgba(102, 128, 153, 0.05); border: 0px solid rgba(0, 0, 0, 0.15); box-shadow: rgba(255, 255, 255, 0.1) 0px 1px 2px inset, rgba(102, 128, 153, 0.05) 45px 0px 0px inset, rgba(102, 128, 153, 0.05) 0px 1px 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
int main()
{
int intValue = 1;
void (^blk)(void) = ^{ printf("intValue = %d\n", intValue); };
blk();
return 0;
}
</pre>
打印结果
intValue = 1
和第一段源码不同的是,这里多了个局部变量 intValue,而且还在 block 里面获取到了。
通过前一段对 block 源码的学习,我们已经了解到 block 的函数定义在 main() 函数之外,那它又是如何获取 main() 里面的局部变量呢?为了解开疑惑,我们再次用 clang 重写这段代码
<pre class="prettyprint linenums prettyprinted" data-anchor-id="a25t" style="padding: 9.5px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 14px; color: rgb(51, 51, 51); border-radius: 4px; display: block; margin: 0px 0px 20px; line-height: 20px; word-break: break-all; overflow-wrap: break-word; white-space: pre-wrap; background: none 0px 0px repeat scroll rgba(102, 128, 153, 0.05); border: 0px solid rgba(0, 0, 0, 0.15); box-shadow: rgba(255, 255, 255, 0.1) 0px 1px 2px inset, rgba(102, 128, 153, 0.05) 45px 0px 0px inset, rgba(102, 128, 153, 0.05) 0px 1px 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
struct __block_impl
{
void *isa;
int Flags;
int Reserved;
void *FuncPtr;
};
struct __main_block_impl_0
{
struct __block_impl impl;
struct __main_block_desc_0* Desc;
int intValue;
__main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int _intValue, int flags=0) : intValue(_intValue)
{
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself)
{
int intValue = __cself->intValue; // bound by copy
printf("intValue = %d\n", intValue);
}
static struct __main_block_desc_0
{
size_t reserved;
size_t Block_size;
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0)};
int main()
{
int intValue = 1;
void (*blk)(void) = (void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, intValue);
((void (*)(__block_impl *))((__block_impl *)blk)->FuncPtr)((__block_impl *)blk);
return 0;
}
</pre>
原来 block 通过参数值传递获取到 intValue
变量,通过函数
__main_block_impl_0 (void *fp, struct __main_block_desc_0 *desc, int _intValue, int flags=0) : intValue(_intValue)
保存到 __main_block_impl_0
结构体的同名变量 intValue
,通过代码 int intValue = __cself->intValue;
取出 intValue
,打印出来。
构造函数
__main_block_impl_0
冒号后的表达式intValue(_intValue)
的意思是,用_intValue
初始化结构体成员变量intValue
。有四种情况下应该使用初始化表达式来初始化成员:
1:初始化const成员
2:初始化引用成员
3:当调用基类的构造函数,而它拥有一组参数时
4:当调用成员类的构造函数,而它拥有一组参数时
至此,我们已经了解了block 的实现,以及获取外部变量的原理。但是,我们还不能在 block 内修改 intValue 变量。如果你有心试下,在 block 内部修改 intValue
的值,会报编译错误
Variable is not assignable(missing __block type specifier)
那么如何在 block 内修改外部变量呢,请看下篇 block没那么难(二):block 和变量的内存管理