Re: Is it safe to assume that viewDidLoad() is only ever called once on iOS 8.0+?
Re: Is it safe to assume that viewDidLoad() is only ever called once on iOS 8.0+?
- Subject: Re: Is it safe to assume that viewDidLoad() is only ever called once on iOS 8.0+?
- From: Quincey Morris <email@hidden>
- Date: Sun, 18 Dec 2016 12:27:50 -0800
- Feedback-id: 167118m:167118agrif8a:167118svog3P8bHC:SMTPCORP
On Dec 18, 2016, at 09:18 , Andreas Falkenhahn <email@hidden> wrote:
>
> Reading the documentation again, it now seems to me that views should
> be created in loadView() instead. The documentation of loadView() says
> that "You can override this method in order to create your views manually."
>
> I've seen lots of code that allocates subviews in viewDidLoad(), though.
> But I guess that's wrong then?
No, it’s not wrong, because you’re talking about subviews.
The purpose of the “loadView” method is to create (if necessary) the view that corresponds to the view controller, and to set the view controller’s “view” property. If you are creating *this* view programmatically, then you should do it in “loadView”. If you are relying on a nib file (even one that just creates a basic view that you configure programmatically), then the documentation says you *must not* override “loadView”.
If you do override it, then it doesn’t matter whether you create subviews (and do other view setup) in “loadView” or “viewDidLoad”, since the second of these will be called just after the first. However, most developers don’t override “loadView”, so they necessarily create [programmatically-created] subviews in “viewDidLoad”.
It’s apparently true that “viewDidLoad” may be called after your application returns the foreground, but it’s not clear whether “loadView” is called in those circumstances. So, if I were you, I’d follow some simple policies to stay within the documented behavior but not risk memory management errors:
1. If you’re creating the view programmatically (i.e. alloc/init), do it in “loadView”.
2. At the start of your “loadView” override, check whether the “view” property is already non-nil. If it is non-nil, do nothing and return immediately.
3. Create subviews in either of the two places. I’d suggest you put any setup that you *would* have put in a nib or storyboard in “loadView”, and dynamically configured setup in “viewDidLoad”.
4. Do memory management safely. That is, keep track of objects you create in “viewDidLoad”, so that if it runs again you know whether you can (a) skip recreating them or (b) release the old ones and retain the new ones. Note that step 2 takes care of this for “loadView”.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden