当块在初始化器中时,在块中捕获变量 [英] Capturing a variable in a Block when the Block is in the initializer

查看:91
本文介绍了当块在初始化器中时,在块中捕获变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下问题:

id observer = [[NSNotificationCenter defaultCenter] 
    addObserverForName:MyNotification 
                object:nil 
                 queue:nil 
            usingBlock:^(NSNotification *note) {
                [[NSNotificationCenter defaultCenter] 
                        removeObserver:observer 
                                  name:MyNotification 
                                object:nil
            ];
            // do other stuff here...
    }
];

我正在使用此模式观察一次通知,然后停止观察它.但是LLVM告诉我(在ARC下),当被块捕获时,变量'observer'未初始化.

I'm using this pattern to observe a notification once and then stop observing it. But LLVM tells me (under ARC) that Variable 'observer' is uninitialized when captured by block.

我如何解决此问题,因为该块必须在初始化之前捕获变量,因为它是初始化程序的一部分?会在observer上使用__block限定符吗?

How can I fix this, since the block necessarily captures the variable before initialization, it being part of the initializer? Will using the __block qualifier on observer do the trick?

推荐答案

如答案中所述

为什么不从NSNotificationCenter:addObserverForName:usingBlock中删除观察者

您必须

  • 添加__block,以便该块将引用已初始化的变量AND
  • 添加__weak,以避免保留周期. (后者仅适用于ARC.如果没有ARC, 该块不会创建对__block变量的 strong 引用.)
  • add __block, so that the block will refer to the initialized variable, AND
  • add __weak, to avoid a retain cycle. (The latter applies only to ARC. Without ARC, the block does not create a strong reference to a __block variable.)

因此:

__block __weak id observer = [[NSNotificationCenter defaultCenter] ...

这篇关于当块在初始化器中时,在块中捕获变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆