Block回顾
Block分为NSStackBlock, NSMallocBlock, NSGloblaBlock。即栈区Block,堆区Block,全局Block。在ARC常见的是堆块。
在ARC中下面四中情况下系统会将栈区中的Block转移到堆区
1:使用了Copy
2:在一个函数中返回值为Block
3:使用了Strong修饰符
4:在方法名中含有usingBlock的Cocoa框架方法或Grand Central Dispatch 的API中传递Block时。
void(^block)(void)=^{ NSLog(@"这是Globle Block"); }; NSLog(@"%@", [block class]); int para = 100; void(^mallocBlock)(void)=^{ NSLog(@"这是Malloc Block, para=%d", para); }; NSLog(@"%@", [mallocBlock class]); NSLog(@"%@", [^{NSLog(@"这是Stack Block, para=%d", para);} class]);
// 输出结果 2019-03-01 16:02:45.571283+0800 RAC[29198:438361] __NSGlobalBlock__ 2019-03-01 16:02:45.571395+0800 RAC[29198:438361] __NSMallocBlock__ 2019-03-01 16:02:45.571493+0800 RAC[29198:438361] __NSStackBlock__
** Block会自动截获自动变量,在不用__block 修饰变量时,块捕获的变量值不会改变。(可以简单等同于值传递和引用传递)
int para = 100; void(^mallocBlock)(void)=^{ NSLog(@"para=%d", para); }; ++para; mallocBlock(); NSLog(@"para=%d", para); __block int other = 100; void(^otherBlock)(void)=^{ NSLog(@"para=%d", other); }; ++other; otherBlock(); NSLog(@"para=%d", other);
// 输出结果 2019-03-01 16:07:18.299909+0800 RAC[29452:446423] para=100 2019-03-01 16:07:18.300076+0800 RAC[29452:446423] para=101 2019-03-01 16:07:18.300173+0800 RAC[29452:446423] para=101 2019-03-01 16:07:18.300253+0800 RAC[29452:446423] para=101