Why does ClassA not keep a reference to ClassC through it's reference to ClassB which is a property of ClassC

Viewed 54

Even though ClassA does not have a direct reference to ClassC. If we inject the same reference of b that ClassA has into ClassC why does ClassC not get retained if it saves this reference to b? Why does this only get retained if we create a reference in ClassA to ClassC directly?

class ClassA {
    var b: ClassB?

    func someFunc() {
        let b = ClassB()
        self.b = b
        let c = ClassC(b: b)
        c.doSomething()
    }
}


class ClassB {}

class ClassC {
    private let b: ClassB
    init(b: ClassB) {
        self.b = b
    }

    func doSomething() {
        print("doSomething")
    }

    deinit {
        print("C deinit")
    }
}

let a = ClassA()
a.someFunc()
1 Answers

You seem to think that the property b in ClassC holds a strong reference to the instance of ClassC that contains it, but that's not true. Properties don't implicitly hold strong references to the thing that contains them. Therefore the local ClassC variable created in someFunc only stays alive until the end of someFunc because nothing is holding a strong reference to it.

Related