简体   繁体   English

引用嵌套块内的弱自我

[英]Referring to weak self inside a nested block

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];
    }

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. 您的代码将正常工作:弱引用不会导致保留周期,因为您明确指示ARC不要增加弱对象的retainCount。 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). 这不会创建保留周期,因为块中的强指针只会在块完成之前存在(它的唯一范围是块本身)。

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

It depends. 这取决于。

You only create a retain cycle if you actually store the block (because self points to the block, and block points to self ). 如果实际存储块,则只创建一个保留周期(因为self指向块,块指向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 . 如果你不打算存储任何一个块,使用对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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM