For a controller that is pushed by a nav controller, if in its desired init method you create the details of the pushed controller’s view, my understanding is that if the view is removed later because it is offscreen (due to low memory, for example), you may never see it again since the init is only called once when loading the view controller, and subsequent pushes may show nothing.
It would seem a better place for this view setup is in the viewDidLoad or viewWillAppear, that way it will be recreated correctly if the controller needs to build the view the next time it is pushed.
Yet I see tutorials that often put the pushed view controller’s view setup in its init method; how important is this?
View setup should be done in
viewDidLoad(or inloadViewif you’re not using a nib), for exactly the reason you’re describing. If you need to know the controller’s top-level view dimensions to set up the subviews, then do it inviewWillAppear:.Usually, a view controller that is popped is immediately deallocated; if the app needs to show the same view later, it creates a new view controller for it. So in that scenario, the app won’t show “nothing”.
If the app pushes or presents another view controller on top of the first view controller, the first view controller’s view can be unloaded. If the app never pushes or presents a second view controller over the first view controller, the first view controller’s view can’t be unloaded until the controller is popped, at which time (in most apps) the controller is deallocated anyway. So in that case, setting up the view in
initwon’t cause trouble.But it’s still bad design to set up views in
init. You might change your app later to push or present a second view controller, thus creating unexpected unsafe behavior.Also, it’s common to create a view controller, set properties on it, and then push it. If the properties affect the controller’s view hierarchy, then
initis too early to set up the views.