-1

I am reading about retain cycle that, "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". But I'm not clear about that concepts. Please can anyone explain retain cycle with real world example.

Thanks.

Dhiman Ranjit
  • 81
  • 2
  • 12
  • Retain cycles can be considered as Deadlocks. If you are not able to find a good example of retain cycle, find one for deadlock. – Vinay Jain Dec 11 '15 at 05:48
  • Retain cycle is all about memory in objective-c management we know that.If you want to know the process with a real life example.Take the case of a form filling in a hall with 1000 people and 10 pens. – Rahul K Rajan Dec 11 '15 at 06:02

2 Answers2

7

A simple example,a person lives in a department,a department have one person(Suppose have one)

@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

Leo
  • 24,596
  • 11
  • 71
  • 92
0

A retain cycle is a situation when object "First" retains object "Second", and object "Second" retains object "First" at the same time*. Here is an example:

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

@interface Second : NSObject {
First *first;
}
@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 First *first;
Rahul K Rajan
  • 776
  • 10
  • 19