简体   繁体   中英

Really best practice to retain IBOutlet view elements?

I keep running into situations with UIViewControllers containing a large amount of IBOutlets connecting the controller to its view's subviews (typically UILabels).

Following "best practices", ie use retain on all UI elements: @property (retain, nonatomic) UILabel *theElement1 , @property (retain, nonatomic) UILabel *theElement2 , ... gives me insane amounts of boiler plate code in dealloc and viewDidUnload for the view controller.

The offending IBOutlets are never used nor set outside the UIViewController (the set-method is only used in viewDidUnload and when the nib is loaded) except automatically when the nib is loaded.

The result from "best practice" is:

  • dealloc littered with [theElement1 release] , [theElement2 release] etc.
  • viewDidUnload with [self setTheElement1:nil] , [self setTheElement2:nil] etc.

However, since all of those elements are known to be retained by the view anyway, and the view is released by the UIViewController at appropriate times, I see absolutely no reason whatsoever for me to manually manage this.

The reason for this particular "best practice" (as far as I can tell) is to be consistent with your retains. But once you start having a large amount of outlets, you're more likely to miss handling the some outlet somewhere in either of the two methods, than you'll have trouble correctly changing outlets to "retain" for those special outlets you really want to retain even after the view is goodbye.

Is there some reason for this "best practice" other than the one I know about or should I feel quite free to break this "rule" in the particular case of subviews to an UIViewController's view?

You should stick to this best practice. It protects you from very bizarre crashes when you access IBOutlets after a memory warning. Yes, you need to manually manage your IBOutlets. Accessorizer does a nice job of automating this code.

Before ObjC 2.0, we had to write all of our accessors by hand, too (@property and @synthesize are very new additions to the language). Things have gotten a lot nicer. As we move to the 64-bit ABI and garbage collection, things get even simpler (and you should expect these things eventually to make their way to iPhone).

But for now, follow the memory management rules as laid out in Memory Management of Nib Objects . You trade a really small amount of typing for a huge amount of debugging. (Hmm, looks like they've updated this doc again; time to study up myself.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM