In my UIViewController subclass should I initialize the NSArray of data for the UIPickerView in init or in viewDidLoad and why? Thanks.
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.
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.
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.
来源:https://stackoverflow.com/questions/1285513/iphone-dev-create-array-in-init-or-viewdidload