xcode ARC 中的保留循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12802396/
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
Retain Cycle in ARC
提问by Raj
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
我从未从事过非基于 ARC 的项目。我刚刚在我的基于 ARC 的项目中遇到了一个僵尸。我发现这是因为保留周期。我只是想知道什么是保留周期。可以
Could you give me an example for retain cycle?
你能给我一个保留周期的例子吗?
回答by dasblinkenlight
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:
保留周期是对象A
保留对象B
,对象同时B
保留对象A
的情况*。下面是一个例子:
@class Child;
@interface Parent : NSObject {
Child *child; // Instance variables are implicitly __strong
}
@end
@interface Child : NSObject {
Parent *parent;
}
@end
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:
您可以通过为“反向链接”使用__weak
变量或weak
属性来修复 ARC 中的保留循环,即链接到对象层次结构中的直接或间接父级:
@class Child;
@interface Parent : NSObject {
Child *child;
}
@end
@interface Child : NSObject {
__weak Parent *parent;
}
@end
**这是最原始的保留循环形式;可能有一长串对象将彼此保留在一个圆圈中。
回答by Simon Germain
Here's what a retain cycle is: When 2 objects keep a reference to each other and are retained, it creates a retain cycle since both objects try to retain each other, making it impossible to release.
这是什么是保留循环:当两个对象保持对彼此的引用并被保留时,它会创建一个保留循环,因为两个对象都试图相互保留,从而无法释放。
@class classB;
@interface classA
@property (nonatomic, strong) classB *b;
@end
@class classA;
@interface classB
@property (nonatomic, strong) classA *a;
@end
To avoid retain cycles with ARC, simply declare one of them with a weak
reference, like so:
为避免使用 ARC 保留循环,只需使用weak
引用声明其中之一,如下所示:
@property (nonatomic, weak) classA *a;
回答by Nick McConnell
This is swift, but here's an interactive demo of retain cycles in iOS: https://github.com/nickm01/RetainCycleLoggerExample
这很快,但这里是 iOS 中保留周期的交互式演示:https: //github.com/nickm01/RetainCycleLoggerExample