Search code examples
iosautomatic-ref-countingclass-hierarchyretention

Do we have a retention cycle when a class (middle of hierarchy) is removed?


Situation: Class A (Grandparent class) retains class B (Parent class) and class B(Parent class) retains class C(Child class) then If I removed class B then what would happen, Does class A and class C has a retention cycle and cause memory leaks?


Solution

  • Depends on how did you remove the Class B.

    If I removed class B then what would happen

    What do you mean by that ? If you are using ARC, you are not supposed to call release. So how did you removed the class B then?

    Because Class A is holding the strong reference to class B, class B's retain count is 1. Now the only way you can bring the refrence count of Class B to 0 and let the ARC clean Class B is by setting the strong reference of Class B to nil.

    So, if in your class A if you say,

    self.classBReference = nil;
    

    Then Class B's reference count becomes 0 and obviously class B gets deallocated and because Class B gets deallocated the reference count of class C becomes 0 because Class C was strongly held by class B and class B no longer exists. Hence Class C is now becomes the candidate to be removed by ARC.

    Proof Of Concept :

    Here is my class Declaration

    class A {
        var binstance : B? = B() //Declared as optional because I need to set the reference to nil later :)
    
        deinit {
            print("A deinited")
        }
    }
    
    class B {
        var cinstance = C()
    
        deinit {
            print("B deinited")
        }
    }
    
    class C {
        deinit {
            print("C deinited")
        }
    }
    

    Now I create instance of Class A in my VC, as a result A,B and C will all have reference count of 1.

    var ainstance : A = A()
    

    When I set the ainstance to nil here is the sequence of calls

    self.ainstance.binstance = nil
    

    O/P

    B deinited

    C deinited