当捕获"self"对象时,弱保留的块如何引起保留周期. [英] How can a weakly retained block cause a retain cycle when capturing "self"

查看:70
本文介绍了当捕获"self"对象时,弱保留的块如何引起保留周期.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有属性的类,该属性是对块的弱引用.

I have a class with a property which is a weak reference to a block.

@interface BlockTest : NSObject
    @property (nonatomic, weak) void(^testBlock)();
@end

在课堂上的另一点,我像这样使用此块:

At another point in the class I use this block like this:

- (void)foobar {
    self.testBlock = ^{
        [self doSomething];
    };
}

编译器(Apple LLVM 3.0)抱怨可能存在保留周期,因为在这里强烈捕获了self.但是我看不到这如何导致保留周期,因为该块本身是__weak引用,因此应该没问题.如果我正确地理解了ARC弱引用,那么当-foobar方法返回时,传递给self.testBlock的块应该被释放(如果没有保存在其他地方),从而释放self.

The compiler (Apple LLVM 3.0) complains that there might be a retain cycle because self is strongly captured here. But I fail to see how this leads to a retain cycle because the block itself is a __weakreference, so it should be fine. If I understood ARC weak references correctly, when the -foobar method returns the block passed to self.testBlock should be deallocated (if not held elsewhere) and thus also release self.

编译器仍然认为可能存在保留周期的原因是什么?

What's the reason the compiler still thinks there might be a retain cycle?

推荐答案

无论如何引用块本身,块都会强烈捕获其中的对象.保留周期警告仅是对可能性的警告.如果您根据应用程序的上下文知道这种使用不会导致保留周期,则可以放心地忽略它.要摆脱警告,您可以通过以下方式通过自我干预:强或弱:

Blocks strongly capture objects within them regardless of how the block itself is referenced. The retain cycle warning is just that, a warning of the possibility. If you know based on the context of your app that this use will not cause a retain cycle you can safely ignore it. To get rid of the warning, you can pass self through an intermediary, strong or weak, as follows:

__weak typeof(self) weakSelf = self;
self.testBlock = ^{
    [weakSelf doSomething];
};

我将您的块属性更改为强引用,并执行上述操作.

I'd change your block property to be a strong reference and do the above.

这篇关于当捕获"self"对象时,弱保留的块如何引起保留周期.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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