1

Let's say I programmatically create a UILabel and then add it as a subview to the main view of my own UIViewController's subclass. I also want to store a reference to it at the class level of my view controller so I can use it later. Should I make it a weak reference? And more importantly why?

I see people do this all the time, and I don't understand it. I thought the point of a weak reference was to avoid a retain cycle, but there's no retain cycle here.

I certainly see this all over code where people use storyboards/nibs (which I've never tried to use so I understand at only a very basic level) but even there I don't understand why weak references would be appropriate. There's no retain cycle there either, right?

Erik Westwig
  • 713
  • 4
  • 16
  • I wasn't thinking this was a duplicate of what you referenced since my primary concern was programatic creation of sub-views not outlets. – Erik Westwig Aug 09 '17 at 23:26

1 Answers1

1

No, there's no reason for that to be a weak reference, you have correctly identified it as a one-way relationship. The Interface Builder code generator has, in the past, generated weak references by default (which may be why you have seen it a lot.) Apple's guidance on this has changed over time, you can read about it here: Should IBOutlets be strong or weak under ARC?

jlew
  • 10,491
  • 1
  • 35
  • 58
  • The question is about a programmatically-created subview, not an IBOutlet. – Joshua Kaden Aug 09 '17 at 19:59
  • @JoshuaKaden: He mentioned storyboards/nibs in the question, so I added that detail for clarity. – jlew Aug 09 '17 at 20:15
  • @JoshuaKaden - Plus, the issue is the largely the same. The view hierarchy will keep a strong reference, so you don't need to keep a strong reference to it. But `weak` references aren't free (admittedly, largely negligible overhead). Also, when programmatically creating a subview that you are going to save in some weak reference, you have to write code that keeps the subview in some local variable while you add the view to your hierarchy and save the reference. Bottom line strong references yield simpler code, which is good as long as there are no reference cycles. – Rob Aug 09 '17 at 20:18