ios 在嵌套块中引用弱自我

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17104634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:57:12  来源:igfitidea点击:

Referring to weak self inside a nested block

iosmemory-managementautomatic-ref-countingblockretain-cycle

提问by Enzo Tran

Suppose I already create a weak self using

假设我已经使用

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

Inside that block, if I nest another block:

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

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

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

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

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

采纳答案by George Karpenkov

It depends.

这取决于。

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

只有在实际存储块时才创建保留循环(因为self指向块,块指向self)。如果您不打算存储任何一个块,使用对的强引用就self足够了——块将在执行后首先被释放,然后它会释放它的指针self

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

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

回答by Gianluca Tranchedone

Your code will work fine: the weak reference will not cause a retain cycle as you explicitly instruct ARC not to increase the retainCount of your weak object. For best practice, however, you should create a strong reference of your object using the weak one. This won't create a retain cycle either as the strong pointer within the block will only exist until the block completes (it's only scope is the block itself).

您的代码可以正常工作:弱引用不会导致保留循环,因为您明确指示 ARC 不要增加弱对象的保留计数。但是,对于最佳实践,您应该使用弱引用创建对象的强引用。这也不会创建一个保留循环,因为块中的强指针只会在块完成之前存在(它的唯一范围是块本身)。

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