引用嵌套块内的弱自我 [英] Referring to weak self inside a nested block

查看:92
本文介绍了引用嵌套块内的弱自我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经使用

__weak typeof(self) weakSelf = self;
[self doABlockOperation:^{
        ...
    }];

在该区块内,如果我嵌套另一个区块:

Inside that block, if I nest another block:

[weakSelf doAnotherBlockOperation:^{
            [weakSelf doSomething];
}

会创建一个保留周期吗?我是否需要为weakSelf创建另一个弱引用?

will it create a retain cycle? Do I need to create another weak reference to the weakSelf?

__weak typeof(self) weakerSelf = weakSelf;
[weakSelf doAnotherBlockOperation:^{
                [weakerSelf doSomething];
    }


推荐答案

取决于。

如果实际存储块,则只创建一个保留周期(因为 self 指向块,而块指向)。如果你不打算存储任何一个块,使用对 self 的强引用就足够了---块将在执行后首先释放,然后它将释放它指向 self 的指针。

You only create a retain cycle if you actually store the block (because self points to the block, and block points to self). If you don't intend to store either of the blocks, using the strong reference to self is good enough --- block will be released first after it got executed, and then it will release it's pointer to self.

在您的特定示例中,除非您执行的操作更多没有显示,你不需要创建任何弱者WevenWeakerSelfs。

In your particular example, unless you're performing more operations which are not shown, you don't need to create any weakerWeakerEvenWeakerSelfs.

这篇关于引用嵌套块内的弱自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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