1. 三种类型
Block有如下三种类型
- NSConcrateGlobalBlock 全局
- NSConcrateStackBlock 栈
- NSConcrateMallocBlock 堆
1. NSConcrateGlobalBlock 位于全局区
当我们声明一个Block,如果这个block没有捕获外部变量,那么这个Block就位于全局区,此时对NSGlobal的retain、copy、release都是无效的,ARC、MRC都是如此
- (void)blockType {
void(^block1)(void) = ^{
};
NSLog(@"-- block1 = %@", [block1 class]);
}
2021-05-17 17:36:02.791048+0800 MemoryManageDemo[37503:5056528] -- block1 = __NSGlobalBlock__
2. NSConcrateStatckBlock 栈区
block捕获了外部变量,但是没有强引用这个block,直接打印出来
//NSConcrateStackBlock
int a = 10;
NSLog(@"-- block2 = %@",[^{
NSLog(@"-- a = %@",a);
} class]);
2021-05-17 18:35:27.662072+0800 MemoryManageDemo[57159:5148084] -- block2 = __NSStackBlock__
3. NSConcrateMallocBlock 堆区
ARC环境下只有捕获了外部变量,并且有强引用指向该Block(或做为函数返回值),系统就会自动将NSStackBlock copy到堆上,就是NSConcrateMallocBlock
//NSConcrateMallocBlock
int b = 10;
void(^block3)(void) = ^{
NSLog(@"-- b = %d", b);
};
NSLog(@"-- block3 = %@", [block3 class]);
2021-05-17 18:37:36.525794+0800 MemoryManageDemo[57425:5151753] -- block3 = __NSMallocBlock__
关于Block源码解析的博客:
Block技巧与底层解析
网友评论