iosobjective-cretain-cycle

Explain Objective C retain cycle with real world example?


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.


Solution

  • 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