Question

Fairly straightforward question in two parts.

  1. If a view retains its subviews, and we create a view hierarchy in Interface Builder where views are nested within others, why does the IBOutlet property for the nested subviews need to be set to retain? Wouldn't assign be an acceptable parameter for those subview properties?

  2. I have a UIView subclass which adds a few subviews to itself upon initialization. To capture references to specific subviews, @property (nonatomic, assign) will suffice for that need, correct? For example, the main UIView adds a player score subview, then later wants to talk to that player score to update it. That reference only needs to be assigned, as the view proper is automatically retain by the UIView class, right?

Was it helpful?

Solution

1) It doesn't need to be. assign is fine. What made you think that you have to use retain?

2) Yes

By the way, are you using ARC? If so, use weak instead of assign (please don't ask why, it is well explained in every corner of stack overflow and the Internet in general).

OTHER TIPS

Yes, it is true that in your case the subview will be retained by the view, so we don't technically need to retain it again. However, that is kind of fragile. What if in the future you add some code that removes that subview from its superview? Then you have a dangling pointer unless you make sure to nil it out.

It is general convention to retain instance variables, unless it is necessary not to (e.g. for delegates). If we go down the path of saying "oh we don't need to retain this instance variable because it's retained here; oh we do need to retain this other one because it's not retained; etc.", then we end up with very haphazard memory management, where every time we add an instance variable, we have to go and think about whether it is retained by something else or not; and then every time we use it, we have to remember whether we decided to retain it or not. It is precisely the kind of memory management nightmare that the memory management rules are designed to avoid.

And retaining the instance variable, what harm does it do? In this case, it just causes an additional retain and release when we assign it. Not a big deal, for the benefit of simplicity and consistency.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top