Objective-c – When should I use Strong vs Weak for IBOutlets (further clarification)

cocoaiboutletobjective c

I thought I understood it clearly from this question –> Should IBOutlets be strong or weak under ARC? but I recently had a discussion which left me totally confused. Can someone just confirm if the following is correct? (if this is a duplicate I didn't mean to break any rules.. just need clarification as I can understand diagrams better than words..)

enter image description here

Under ARC (MacOSx)

  1. view1 = strong
  2. MainView = weak (In WindowControllerA)
  3. MainView = strong (In ViewControllerB)
  4. view2 = strong
  5. view3 = weak (In ViewcontrollerB)
  6. view3 = strong (In ViewControllerC)

If this is correct then can someone confirm please..

In the diagram above, we have a windowControllerA that is on the screen. In windowControllerA's view, there are 2 NSViews. view1 belongs to the windowController, but mainView belongs to the view of the instianciated viewController, ViewControllerB.

ViewControllerB also contains 2 views within its mainView. View2 is owned by viewControllerB while view3 belongs to another instanced viewController, ViewControllerC.

ViewController C has one view which it owns.

Best Answer

Most outlets for subviews don't need to be strong references because, after all, they're subviews loaded as part of a view hierarchy. As long as the top-level view exists, and as long as you don't go removing the subviews from their parents, the subviews in the view hierarchy will be retained by their parents for the lifetime of the top-level view.

In the days before ARC, some people were happy to rely on the view hierarchy to retain their views for them and so set their outlet properties to assign. Others didn't like the idea that a hiccup in the view hierarchy could leave them with a handful of dangling pointers, and so set their properties to retain. ARC gives us zeroing weak references, so that your outlets will be set to nil if the objects they point to are deallocated, and that makes using weak references for outlets seem a lot safer. On the other hand, if you want to maintain a reference to a view even if the view hierarchy that contains is is deallocated, you should set that reference to strong.

Since your view controller is responsible for the view hierarchy it manages (i.e. "owns"), it should have a strong reference to the top-level view. You don't need to worry too much about this, as the view property of any UIViewController-derived view controller is set to retain (i.e. strong).