Why set a hold on @property for subviews?

Quite a simple question in two parts.

  • If a view retains its child objects, and we create a view hierarchy in Interface Builder where views are nested within others, why does the IBOutlet property for nested subviews need to be saved to persist? Wouldn't an acceptable parameter be assigned to these subview properties?

  • I have a UIView subclass that adds multiple subrequests when initialized. To grab references to specific subclauses, @property (nonatomic, assign) will suffice for that need, right? For example, the main UIView adds a player subquery and then wants to talk to that player account to update it. This link should only be assigned because the view is automatically saved by the UIView class, right?

+3


source to share


2 answers


1) This is optional. assign

fine. What made you think what you need to use retain

?

2) Yes



By the way, are you using ARC? If so, use weak

instead assign

(please don't ask why, this is well explained in every corner and on the internet in general).

+2


source


Yes, it's true that in your case the subview will be saved in the view, so we don't technically need to save it again. However, it is rather fragile. What if in the future you add some code that removes this subview from your supervisor? Then you have a dangling pointer if you don't make sure it's not there.

A general convention is to keep instance variables unless needed (for example, for delegates). If we go down the path saying, "Oh, we don't need to store this instance variable because it is being stored here, oh, we need to keep this other one because it hasn't been preserved, etc." Then we find ourselves very random memory management, where every time we add an instance variable we have to think about whether it is being saved by something else or not; and then every time we use it, we have to remember whether we decided to keep it or not. It is such a memory management nightmare that drives the rules of memory management.



And by storing an instance variable, what harm does it do? In this case, it just calls an additional save and release when we assign it. It doesn't matter in the interest of simplicity and consistency.

+1


source







All Articles