Would this be prone to retain cycle leak?

Hello. After having read some literature on memory management, I am wondering whether the following code would be prone to retain cycle memory leaks:


class ClassA_VC: UIViewController
{
   let objectB = ClassB()

   func funcA()
   {
        let objectC = ClassC()

        objectB.funcB()
        objectC.funcC()
        ClassD.funcD()
   {
}

class ClassB
{
     func funcB()
     {
        let objectC = ClassC()
        objectC.funcC()
        ClassD.funcD()
     }
}

class ClassC
{
     func funcC()
     {
        let objectB = ClassB()
        objectB.funcB()
     }
}

class ClassD
{
     static func funcD()
     {
        let objectB = ClassB()
        objectB.funcB()
     }
}


Note that with the exception of object to ClassB in line 3, all other objects are initialized inside methods.


Thanks a lot!

Replies

I'm not sure why you think your code would make cyclic references.


The only strong reference bound to an instance is `objectB` of `ClassA_VC`, and an instance of `ClassB` does not have any strong reference to any other instances. Thus, your code does not make cyclic references.

Thank you. This is what I thought, but I wanted to check.


Also, is it also safe to have a singleton object in all four classes declared as follows? My understanding is that it is totally safe and does not create any retain cycles.


let appSingleton = IGASingleton.sharedInstance


Thank you!

It depends on how you have defined your singleton. Usually, a singleton instance is bound to a static variable and you have no need to worry abount cyclic references.


I remember I should have note one things.

If your code:

let appSingleton = IGASingleton.sharedInstance

is written as a property declaration of any classes, which the singleton instance may have strong refenrence to, you may need to consider the possibility of cyclic references. You should better not have strongly referenced properties to singletons.