用真实世界的例子解释目标C的保留周期



我读到关于保留循环的文章,"保留循环可以有几种形式,但它通常意味着对象A保留对象B,对象B保留对象A,但没有其他东西保留对象A或B"。但我不清楚这些概念。请任何人用现实世界的例子来解释保留周期。

谢谢。

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

@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;
}

你不会看到解除锁定日志,这是保留圈

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

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

您可以通过使用__weak变量或"反向链接"的弱属性来修复ARC中的保留循环,即与对象层次结构中的直接或间接父级的链接:

__weak First *first;

最新更新