In my UIViewController subclass should I initialize the NSArray of data for the UIPickerView in init or in viewDidLoad and why? Thanks.
3 Answers
I would call it in viewDidLoad
as the view can be loaded more than once (and also be unloaded, hence you might also want to reload your array).
Also, it's a good idea to load data lazily on iPhone most of the time. Loading data in viewDidLoad
is much lazier than init
, which might end up performing better for you if you init, but don't immediately use your view controller.

- 11,943
- 14
- 73
- 115
-
Ok that makes sense, but could you tell me when viewDidUnload is called? I know, when the view has unloaded, but when does that happen automatically? How can I unload it manually? – mk12 Aug 17 '09 at 01:36
-
1The view gets unloaded by UIViewController when it recieves a memory warning, at which point it will call viewDidUnload. If you do create your array in viewDidLoad, you must make sure to destroy it in viewDidUnload. You must also be sure it will never be accessed if the view is not visible (views never get unloaded if visible). If you do need access to it (for example, to update it) even when your view isn't visible, I'd recommend creating it in init. Apple recommends using viewDidLoad only for objects that can easily be recreated. – T . Aug 17 '09 at 12:22
-
An alternative to creating it in init is defining the array as a property and lazily create the array the first time it gets accessed. The end result is the same as the init method, but if you never access the array, it won't be using memory. – T . Aug 17 '09 at 12:24
It depends on exactly what you intend the array to store, and how you intend to initialize it. viewDidLoad
can be called multiple times (especially after a low memory warning is sent to your program - inactive view controllers will unload their views, then reload them when the become active or visible again), whereas init
will generally only be called once for the lifetime of the object.

- 59,527
- 19
- 156
- 165
One case for doing this in init, is that viewDidLoad can be called after viewWillAppear. If you rely on the array being present at that time, you may need to put the initialization in init.
Generally speaking, viewDidLoad is a pretty good place as long as you keep in mind it could be called more than once.

- 74,769
- 26
- 128
- 150