在 ARC 中保留周期



我从未从事过非基于ARC的项目。我刚刚在基于 ARC 的项目中遇到了一个僵尸。我发现这是因为保留周期。我只是想知道什么是保留周期。能

你能给我举一个保留周期的例子吗?

保留

循环是对象A保留对象B的情况,而对象B同时保留对象A*的情况。下面是一个示例:

@class Child;
@interface Parent : NSObject {
    Child *child; // Instance variables are implicitly __strong
}
@end
@interface Child : NSObject {
    Parent *parent;
}
@end

您可以通过使用"反向链接"的__weak变量或weak属性(即指向对象层次结构中直接或间接父级的链接)来修复 ARC 中的保留周期:

@class Child;
@interface Parent : NSObject {
    Child *child;
}
@end
@interface Child : NSObject {
    __weak Parent *parent;
}
@end


*这是保留周期的最原始形式;可能有一长串物体在一个圆圈中相互保留。

下面是保留循环:当 2 个对象相互保留引用并被保留时,它会创建一个保留循环,因为两个对象都试图相互保留,因此无法释放。

@class classB;
@interface classA
@property (nonatomic, strong) classB *b;
@end

@class classA;
@interface classB
@property (nonatomic, strong) classA *a;
@end

为了避免使用 ARC 保留周期,只需使用weak引用声明其中一个循环,如下所示:

@property (nonatomic, weak) classA *a;

很快,但这里有一个 iOS 中保留周期的交互式演示: https://github.com/nickm01/RetainCycleLoggerExample

最新更新