2
votes

When memory is low and views get cleaned up by the OS, my understanding is that viewDidUnload is an appropriate place to clean up objects and memory used by your UIViewController (that otherwise wouldn't get cleaned up as a function of being in the view hierarchy). This data is then re-initialized when loadView is called again to create the view. Can someone give examples of what sort of things might be cleaned up (and likewise initialized in loadView)?

I have some data I initialize in loadView currently which sets the stage for my view controller to run a complex animation script involving captions, images, etc. I figured it would make sense to release and cleanup that data if my view were to be removed by the OS (and viewDidUnload were called), but then I thought to myself, why wouldn't I just initialize that data within init and clean it up in dealloc instead of repeatedly initializing and cleaning up the same data (it doesn't change as a function of when the view is loaded or shown). Would this be a better place for it?

Basically, my thinking is:

  1. yes, i should just initialize it in init and release in dealloc because it never changes
  2. initializing things in loadView (and subsequently cleaning in viewDidUnload) is an appropriate practice when either that data will initialize differently based upon when the view is loaded (or even more appropriately when the view appears in viewWillAppear/viewWillDisappear) or it is a good candidate for freeing memory because it takes up a lot of memory that you'd like to see freed up if the view is not active.

Can anyone give me some clarification on my questions and/or my line of thinking?

1

1 Answers

0
votes

if you're going to be going back and forth between that view and another and the viewcontroller will be kept around, you could indeed move the initialisation to init, and clean it up in dealloc. but what you would want to do is also clean it up in - (void)didReceiveMemoryWarning (be careful not to use self.view in didReceiveMemoryWarning otherwise that'll reload the view :) ). then you could use lazy loading to reload it in viewDidLoad (i.e. if it doesn't already exist then initialise the data, otherwise don't).

of course, you can't do any initialisation in init that depends on the view being present.. viewDidLoad is the place for that.