简体   繁体   English

保持周期关注

[英]Retain cycle concern

I took over project from another company and I often see this part of code when assigning value to variable: 我从另一家公司接手了项目,并且在为变量赋值时经常看到这部分代码:

// interface:
@property NSArray *foos;


// somewhere in implementation:
BOOL foosExist = ^BOOL {
    return self.foos.count > 0; // self inside block
}();

Moreover compiler claims when referencing inside block to foos property by underlying variable _foos : 此外,编译器声称通过基础变量_foos引用内部块中的foos属性时:

Block implicitly retains "self"; 块隐式保留“自身”; explicitly mention "self" to indicate this is intended behavior. 明确提及“自我”以表明这是预期的行为。

Does this self inside block truly creates retain cycle? 这个自我内在的阻拦真的创造了保留周期吗? If not, why? 如果没有,为什么? Can someone elaborate? 有人可以详细说明吗?

There is no cycle in your example. 您的示例中没有循环。

Your block is simply a value created during the evaluation of an expression and them immediately applied to produce a BOOL value. 您的块只是在表达式求值期间创建的值,它们立即应用于生成BOOL值。

While your situation is unusual, creating a block to immediately apply it in the same expression, a similar situation occurs when you pass a block to another method, either directly or by storing it in a local variable and passing the variables value - no cycle is created. 虽然您的情况很不正常,创建一个块以立即将其应用于相同的表达式中,但是当您将一个块直接或通过将其传递给另一个方法或通过将其存储在局部变量中并传递变量的值传递时,也会发生类似的情况-没有循环创建。

If instead you created the same block but stored it into an instance variable ( not a local variable), then self would reference the block, the block would reference self , and you would have a cycle. 相反,如果您创建了相同的块但将其存储到实例变量( 而不是局部变量)中,则self将引用该块,该块将引用self ,并且您将有一个循环。 That is not in itself bad, it only becomes bad if the cycle is never broken, which causes a leak. 这本身并不坏,只有在循环永不中断的情况下,它才变为坏,这会导致泄漏。 However if at some point the cycle is broken, say by writing a different value into the instance variable, then the cycle never becomes an issue. 但是,如果在某个时刻中断了循环(例如,通过将不同的值写入实例变量),则该循环永远不会成为问题。

HTH 高温超导

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

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