Bruno Morgado
Bruno Morgado

Reputation: 507

How to avoid memory leaks with child viewControllers

imagine a ViewController which is comprised of multiple child ViewControllers as depicted below:

ViewController1:
- ViewController2
- ViewController3

ViewController2 does not change so it is defined on the Storyboard with containerViews. In order to get reference of ViewController2 by ViewController1 I do the following:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destination = segue.destination
        if let viewController2 = destination as? ViewController2 {
            self.viewController2 = viewController2
        }
   }

As for ViewController3, it is dynamic so it is added programmatically in ViewController1 like so:

    addChildViewController(viewController3)
    view.addSubview(viewController3.view)
    viewController3.didMove(toParentViewController: self)

My question is, for both these scenarios, what is the proper way of handling the memory management of the references of viewController2 and viewController3. Should they be weak or strong references?

Thanks!

Upvotes: 0

Views: 1405

Answers (1)

Duncan C
Duncan C

Reputation: 131408

The basic rule of thumb is to have all references in the "outward" direction be strong, and "backwards" references be weak.

In your case ViewController1 is the base view controller. It owns ViewController2 and ViewController3, so those references should be strong. ViewController2 and ViewController3 point back to view controller 1, so their references should be weak.

Think of your object graph as a tree. It's anchored to the UIApplication at the root, and everything is anchored to that. Objects higher up the tree should be owned by their root objects, but should not have owning references to their root objects.

Upvotes: 1

Related Questions