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

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

问题描述

假设我已经使用

__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.

在您的特定示例中,除非您执行更多未显示的操作,否则您无需创建任何 weakerWeakerEvenWeakerSelfs.

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天全站免登陆