block 的 copy 以及 block 使用外部变量

最近在想,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 之后,还是正常销毁了,没有发生内存泄露问题。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,911评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,014评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,129评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,283评论 1 264
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,159评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,161评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,565评论 3 382
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,251评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,531评论 1 292
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,619评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,383评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,255评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,624评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,916评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,199评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,553评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,756评论 2 335

推荐阅读更多精彩内容