views:

1411

answers:

4

In my UIViewController subclass should I initialize the NSArray of data for the UIPickerView in init or in viewDidLoad and why? Thanks.

A: 

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.

Tim
+1  A: 

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.

jbrennan
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
The 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.
Toon Van Acker
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.
Toon Van Acker
A: 

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.

Kendall Helmstetter Gelner
A: 

I have a question, since you guys says that ViewDidLoad can be called multiple times, but how come that I can only call it once?? I did [self removefromsuperview], and the view disapperared, then I click the button at mainView to add the view again, but the viewdidload never get called, how can I make it be called multiple times??

Georg
This is a question, not an answer.
Mk12
sorry for that, yes I was asking a question....
Georg