0

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!

Bruno Morgado
  • 507
  • 1
  • 8
  • 26
  • 2
    As long as VC2 and VC3 don't have a strong reference to VC1, there is no reference cycle. Instead of worrying about non-existent issues, verify whether you actually have a problem or not. Use Instruments or verify `deinit` is called. Once you have an actual issue, post a question with relevant specifics. – rmaddy Feb 05 '18 at 19:07
  • Why are you posting a second question about memory leaks 9 minutes after this one? https://stackoverflow.com/questions/48629539/how-to-avoid-memory-leaks-with-nested-objects –  Feb 05 '18 at 19:13
  • When you do `addChildViewController` (or have it as a embedded container), that keeps a strong reference to the child controller. So you don’t have to worry about keeping your own strong reference to it. But you can, if you want. But there is no strong reference cycle here. – Rob Feb 05 '18 at 19:41

1 Answers1

1

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.

Duncan C
  • 128,072
  • 22
  • 173
  • 272