Thursday, June 2, 2011

duh: multiple calls to viewDidLoad

Somehow I've been writing iPhone apps for nearly three years, yet still didn't "get" (or perhaps just didn't remember) that a UIViewController's viewDidLoad method may be called multiple times. This means that I have occasionally been putting code into viewDidLoad that I assumed would only be run once per UIViewController instance.

Wrong wrong wrong.

Even beginner iOS coders know that if a memory warning occurs, hidden views are unloaded to free space for new objects - What I didn't think about (or remember) is that when the freed view needs to be used again, those views are reloaded using viewDidLoad.

Here's an example of the problem:

In the app I'm working on, I'm programmatically adding a subview in viewDidLoad. That subview's purpose is to display a picture and allow users to select from the camera roll or UIImagePickerController - To support various operations, my subview includes a data object which is initialized in viewDidLoad. In normal operations, when the parent view controller exits, it saves off the URL of the picture from the subview's data object.

However, on a device (it works great on the simulator), when the UIImagePickerController is shown, it creates a memory warning which causes my subview to be freed. When the UIImagePickerController is released, it then calls viewDidLoad again to recreate that subview, thus losing any modifications (e.g. URL) to the data object.

So that I don't forget this again, this goes into the save.txt file.

No comments:

Post a Comment