保持ARC的周期 [英] Retain Cycle in ARC
问题描述
我从未从事过非基于ARC的项目.我刚在基于ARC的项目中遇到了一个僵尸.我发现这是因为保留周期.我只是想知道什么是保留周期.可以
I have never worked on non ARC based project. I just came across a zombie on my ARC based project. I found it was because of retain cycle.I am just wondering what is a retain cycle.Can
能给我一个保留周期的例子吗?
Could you give me an example for retain cycle?
推荐答案
当对象A
保留对象B
,而对象B
同时保留对象A
时,保留周期是一种情况. > * .这是一个示例:
A retain cycle is a situation when object A
retains object B
, and object B
retains object A
at the same time*. Here is an example:
@class Child;
@interface Parent : NSObject {
Child *child; // Instance variables are implicitly __strong
}
@end
@interface Child : NSObject {
Parent *parent;
}
@end
您可以通过为<反向链接>使用__weak
变量或weak
属性来修复ARC中的保留周期,即指向对象层次结构中直接或间接父级的链接:
You can fix a retain cycle in ARC by using __weak
variables or weak
properties for your "back links", i.e. links to direct or indirect parents in an object hierarchy:
@class Child;
@interface Parent : NSObject {
Child *child;
}
@end
@interface Child : NSObject {
__weak Parent *parent;
}
@end
* 这是保留周期的最原始形式;可能有很长的物体将它们彼此围成一圈.
* This is the most primitive form of a retain cycle; there may be a long chain of objects that retain each other in a circle.
这篇关于保持ARC的周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!