2

Should references to subviews be weak?

In other words, will this code cause retain cycle after initializing CustomView instance, adding it to view hierarchy and calling setupUI function?

class CustomView: UIView {
  let subview = UIView()

  func setupUI() {
    self.addSubview(subview)
  }
}
Edgar
  • 105
  • 9

2 Answers2

4

will this code cause retain cycle ... ?

No, it will not cause strong reference cycle (previously known as “retain cycle”). You can safely use strong reference in this case.

You only get strong reference cycles when two (or more) objects have strong references to each other. But your subview has no strong references back to its superview, so there is no risk of a strong reference cycle here. And if your subview did need a reference back up to its superview (e.g. delegate-protocol pattern, completion handler closures, etc.), that’s the reference that you’d make weak, not the reference that CustomView has to subview.

Should references to subviews be weak?

When you call addSubview, that adds the subview to the view hierarchy, which coincidentally establishes its own strong reference to this new subview. For this reason, if you are creating your own reference to this subview after adding it to the view hierarchy, it technically doesn’t matter if this reference is weak or strong. It can be weak (because the view hierarchy is maintaining a strong reference for you) or it can be strong (because you have no reference cycle). You don’t need to keep your own reference to subview at all if you don’t want, confident that that the view hierarchy will keep the necessary strong reference to it.

Now, in your particular example, you are defining your subview before adding it to the view hierarchy, so you happen to need to use a strong reference to make sure it isn’t deallocated before you call setupUI. But, in contrast, when defining @IBOutlet references, you generally can safely use either weak or strong references without incident.

I would certainly suggest strong references where it results in natural code (like your example). And there are cases where weak references are clearly preferable (e.g. a subview that might be removed later ... it saves us from having to manually nil the references). Regarding a general rule of “should subviews use weak references”, while conventional wisdom has shifted to “use strong references” (e.g. Should IBOutlets be strong or weak under ARC?), there’s nothing substantively wrong with weak references, so I’d suggest just picking a convention and sticking with it.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
2

According to Docs

addSubview

This method establishes a strong reference to view and sets its next responder to the receiver, which is its new superview

No retain cycles between parent view and it's subviews , subviews can be addded/removed and when superview is deallocated it'll dealloocate the childs also

Community
  • 1
  • 1
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87