简体   繁体   English

什么时候在块中引用自身?

[英]When is reference to self in block a retain cycle?

I've got a problem that is probably fairly common. 我遇到了一个可能很普遍的问题。 In an ARC environment, a block that needs to reference self will outlive self. 在ARC环境中,需要引用自身的块将失效。 I'm aware of the convention to use __weak typeof(self) weakSelf = self; 我知道使用__weak typeof(self) weakSelf = self; in blocks to avoid retain cycles. 以块为单位,以避免保留周期。 The problem is that we do need to retain self. 问题是我们确实需要保持自我。 So my question is: When does a reference to self in a block create a retain cycle? 所以我的问题是:何时在块中引用self会创建一个保留周期? This post post suggests that in animation blocks, reference to self is ok. 这篇文章建议在动画块中引用self没问题。

I had also considered a solution like the following, but am not sure it changes anything: 我还考虑过以下解决方案,但不确定是否会更改任何内容:

__block typeof(self) blockSelf = self;

[someObj someMethodTakingCallback:^{
    //do some stuff
    blockSelf = nil;
 }];  

如果self除了保留`self之外,还保留了块,您将获得一个参考周期。

In this case you would have a retain cycle if self holds a reference to someObj since someObj is probably holding a reference to self. 在这种情况下,如果self持有对someObj的引用,则将有一个保留周期,因为someObj可能持有对self的引用。 It's actually a retain cycle if there's any retaining reference path from self to someObj. 如果存在从self到someObj的任何保留参考路径,则实际上是一个保留周期。

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

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