Search code examples
xcodeswift4.2retain-cyclememory-graph-debugger

xcode memory graph not show retain cycle


My swift code is below. I have used self in closure but when I run project, memory graph does not show retain cycle. I am wrong about there is a retain cycle?

class ViewController: UIViewController {

    private var counter = 0

    private var closure : (() -> ()) = { }

    func foo() {
        closure()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        closure = {
            self.counter += 1
            print(self.counter)
        }
    }

}

Solution

  • Yes, Xcode does not always visually represent the strong reference cycle. But it is consistent in showing that the object in question has not yet been deallocated.

    For example, if I push via a navigation controller and pop, I see the ViewController in the list of live objects, but when I select it, don’t see any cycle, but rather see some cryptic graph including the navigation controller (even though I popped it off):

    enter image description here

    That having been said, I find that if I present modally and dismiss the view controller in question, I will see the cycle more clearly:

    enter image description here

    It would be nice if we could see the prototypical cycle (like shown below), but the picture isn’t always that simple when dealing with UIKit objects.

    enter image description here