I need to load some data in my UIViewController to show a UIPickerView widget in an iPhone modal view.
I did some research and found this answer in SO. I proceeded to implement my data reading code in initWithNibName:bundle: and data unloading in dealloc. However, Instruments kept telling me there was a memory leak when repeatedly showing the modal view, and during debugging I noticed initWithNibName:bundle: was called each time the view was shown, but dealloc was never called under normal execution (although it’s triggered by a low-memory condition as per Apple’s UIViewController Class Reference document, and the same applies to viewDidUnload).
I ended up loading data in the viewDidLoad: method and I released it in viewDidDisappear:, the widget shows the data and there are no leaks. However, I’d like to know if there are any good practices in regards to this, because on one comment in Apple’s documentation mentions this:
You should not use this method (i.e. viewDidUnload) to release user data or any other information that cannot be easily recreated.
I assumed the right way was load data in viewDidLoad and releasing all references to it in viewDidUnload, but in practice the latter method is not called unless a low-memory condition arises, and consequently each time the view is displayed, the data is loaded again and the reference to the old data is lost, causing the memory leak.
Thanks for your comments.
Something bad is happening if
viewDidLoadis getting called every time your view is shown.viewDidAppearshould get called, butviewDidLoadshould only be called the first time the view is needed and if the view is needed andviewDidUnloadgot called.