Understanding retain cycle in depth

2019-03-08 01:43发布

Lets say we have three objects: a grandparent, parent and child. The grandparent retains the parent, the parent retains the child and the child retains the parent. The grandparent releases the parent.

What will happen in this case ?

9条回答
放我归山
2楼-- · 2019-03-08 02:17

Retain Cycle is the condition 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.


Example: A person lives in a department, a department has one person.

@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

Then call it like this:

- (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.

查看更多
贼婆χ
3楼-- · 2019-03-08 02:20

Retain Cycle is the condition 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.

Here The "Grandparent" retains the "parent" and "parent" retains the "child" where as "child" retains the "parent".. Here a retain cycle is established between parent and child. After releasing the Grandparent both the parent and child become orphaned but the retain count of parent will not be zero as it is being retained by the child and hence causes a memory management issue.

There are two possible solutions:

1) Use weak pointer to parent , i.e a child should be using weak reference to parent, which is not retained.

2) Use "close" methods to break retain cycles.

http://www.cocoawithlove.com/2009/07/rules-to-avoid-retain-cycles.html

查看更多
仙女界的扛把子
4楼-- · 2019-03-08 02:20

When grandparent release the parent the parent is still alive as the child retain the parent.

查看更多
登录 后发表回答