最近在想,block 被 copy 之后内存会有什么变化,block 里面使用的外部变量为什么不会被销毁的问题,目前总结如下。
太长不看版
1.block 被 copy 的时候,block 会被从栈(stack)中移到堆(heap)中,内存地址 MRC 下变化
2.block 里面使用的外部变量(OC 对象)会被 retain 一次,所有 block 执行结束之前,外部变量不会被销毁
3.block 里面使用的外部变量都是“只读”的,想要修改,需要修改变量类型为“__block”
- (instancetype)init {
if (self = [super init]) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
button.frame = CGRectMake(100, 100, 100, 100);
NSLog(@"打印的是 block 定义时候 block 外面 button 的地址 ***** %p", button);
NSLog(@"button retainCount %zd", button.retainCount); // retainCount = 1
void(^tempBlock)() = ^(void) {
//相当于 button 在这里 retain
NSLog(@"这是定义 block 的地方 打印的是 block 里面 button 的地址 ***** %s -- %p", __func__, button);
NSLog(@"button retainCount %zd", button.retainCount); // retainCount = 1
NSLog(@"back");
};
NSLog(@"%@", tempBlock);
self.viewControllerTestBlock = tempBlock;
NSLog(@"button retainCount %zd", button.retainCount); // retainCount = 2
} // button retainCount = 1
return self;
}
block 被 copy 的时候,block 会被从栈(stack)中移到堆(heap)中,关于 block 从 stack 到 heap 地址变化如下(MRC)(但是 ARC 下是没有变化的)
2016-03-24 02:03:05.680 BlockCircle_01[3722:428943] <NSStackBlock: 0x7fff52e65ac8>
2016-03-24 02:03:05.681 BlockCircle_01[3722:428943] <NSMallocBlock: 0x7f9110c4dd30>
block 中使用的 block 外部的局部变量,如果是 OC 对象,这个 OC 对象是会 retain 一次的,MRC 下可以打印出来这个 OC 对象的 retainCount,关于 button 引用计数如下(MRC)
2016-03-24 01:37:52.567 BlockCircle_01[3337:406242] 定义 button 时候 retainCount 1
2016-03-24 01:37:52.568 BlockCircle_01[3337:406242] 定义 button 所在方法将要结束时候 retainCount 2
2016-03-24 01:37:55.635 BlockCircle_01[3337:406242] block 使用 button retainCount 1
但是,这些局部变量在 block 中只是 read 的,不可以修改这些局部变量的值,如果想要修改,需要在外面把这些变量改成 __block 类型的。
文档里面一些资料
Block objects are a C-level syntactic and runtime feature. They are similar to standard C functions, but in addition to executable code they may also contain variable bindings to automatic (stack) or managed (heap) memory. A block can therefore maintain a set of state (data) that it can use to impact behavior when executed.
You can use blocks to compose function expressions that can be passed to API, optionally stored, and used by multiple threads. Blocks are particularly useful as a callback because the block carries both the code to be executed on callback and the data needed during that execution.
Blocks are particularly useful as a callback because the block carries both the code to be executed on callback and the data needed during that execution.
Blocks 作为回调函数使用的时候会更有效,因为 block 不但存储了函数部分,同时执行时候需要的数据也被存储了下来。
Can continue to share and modify state defined within the lexical scope (the stack frame) after the lexical scope (the stack frame) has been destroyed
词法范围内定义的变量,如果在 block 中使用,当 block 被 copy 的时候,会被放到堆(heap)中,在栈中局部变量销毁的时候,还是可以使用这些变量
Typically, you shouldn't need to copy (or retain) a block. You only need to make a copy when you expect the block to be used after destruction of the scope within which it was declared. Copying moves a block to the heap.
一般情况下,block 是不需要被 copy 的,除非你希望在这个 block 声明的词法范围被销毁之后,仍旧可以调用这个 block,copy 会把 block 移到堆(heap)中。
还有一个问题,文档在说 OC 对象和 block 关系的时候,说是“通过引用”和“通过值”,是不一样的,如果“通过引用”使用 OC 对象,就会对 self 有一个强引用,这样是不是就有可能造成循环引用,但是,程序运行是没有问题的,代码放在最下面了。
Objective-C Objects
When a block is copied, it creates strong references to object variables used within the block. If you use a block within the implementation of a method:
If you access an instance variable by reference, a strong reference is made to self;
If you access an instance variable by value, a strong reference is made to the variable.
The following examples illustrate the two different situations:
dispatch_async(queue, ^{
// instanceVariable is used by reference, a strong reference is made to self
doSomethingWithObject(instanceVariable);
});
id localVariable = instanceVariable;
dispatch_async(queue, ^{
/*
localVariable is used by value, a strong reference is made to localVariable
(and not to self).
*/
doSomethingWithObject(localVariable);
});
To override this behavior for a particular object variable, you can mark it with the __block storage type modifier.
- (IBAction)btnDidClick {
__block SXView *smallView = [[SXView alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 200) * 0.5, ([UIScreen mainScreen].bounds.size.height - 200) * 0.5, 200, 200)];
smallView.backgroundColor = [UIColor yellowColor];
[self.view addSubview:smallView];
NSLog(@"smallView ----- %p", smallView);
__weak typeof(self) weakSelf = self;
self.sxViewControllerTestBlock = ^(void) {
weakSelf.view.backgroundColor = [UIColor brownColor];
smallView.backgroundColor = [UIColor purpleColor];
NSLog(@"smallView inside ----- %p", smallView);
};
ViewController *nextViewcontroller = [[ViewController alloc] init];
nextViewcontroller.viewControllerTestBlock = self.sxViewControllerTestBlock;
// presentViewController works like modal(from bottom)
// [self presentViewController:nextViewcontroller animated:YES completion:nil];
[self.navigationController pushViewController:nextViewcontroller animated:YES];
}
- (void)dealloc {
NSLog(@"***** %@ dealloc *****", [self class]);
}
对 smallView 引用,但是,控制器 pop 之后,还是正常销毁了,没有发生内存泄露问题。
网友评论