用真实世界的例子解释 Objective C 保留循环?

Explain Objective C retain cycle with real world example?

我正在阅读有关保留周期的内容,"A retain cycle can take a few forms, but it typically means that object A retains object B, and object B retains object A, but nothing else retains object A or B"。但我不清楚这些概念。请任何人都可以用真实世界的例子解释保留周期。

谢谢。

循环引用是对象"First"保留对象"Second",对象"Second"同时保留对象"First"的情况*。这是一个例子:

@class Second;
@interface First : NSObject {
Second *second; // Instance variables are implicitly __strong
}
@end

@interface Second : NSObject {
First *first;
}
@end

您可以通过使用 __weak 变量或 "back links" 的弱属性来修复 ARC 中的保留周期,即链接到对象层次结构中的直接或间接父级:

__weak First *first;

一个简单的例子,一个人住在一个​​部门,一个部门有一个人(假设有一个)

@class Department;

@interface Person:NSObject
@property (strong,nonatomic)Department * department;
@end

@implementation Person
-(void)dealloc{
    NSLog(@"dealloc person");
}

@end
@interface Department: NSObject
@property (strong,nonatomic)Person * person;
@end

@implementation Department
-(void)dealloc{
    NSLog(@"dealloc Department");
}
@end

然后这样称呼它

- (void)viewDidLoad {
    [super viewDidLoad];
    Person * person = [[Person alloc] init];
    Department * department = [[Department alloc] init];
    person.department = department;
    department.person = person;
}

You will not see dealloc log,this is the retain circle