Reputation: 337
I've been browsing some answers here and I get two different suggestions:
ViewDidLoad
. Suggested in this answerWhich one is the current best practice? The second answer seems to be older (2010), so I wonder if it's an old, no-longer-suggested, practice?
Upvotes: 3
Views: 2625
Reputation: 45598
For a non-XIB-based view controller, the correct place is in -loadView
. -loadView
is responsible for initializing a view controller's view
property, including any subviews. The system will call this method at the appropriate time. You must assign something to the view controller's view
property inside this method:
- (void)loadView
{
UIView *view = ...;
// create additional views here
self.view = view;
}
If you have a XIB-based view controller, the documentation says not to override -loadView
. In this case, you should do additional view initialized work in -viewDidLoad
.
Upvotes: 8
Reputation: 3774
No, never do such stuff in init.
I viewDidLoad or even viewWillAppear, never in init because your view might not be there at the time, it kept happening to me when I was starting out that I was setting some string to a UILabel which wasn't there and made the app crash, but this worked in the simulator because it is so much faster than an actual device like iPhone 3.
Same with resetting data and closing off delegates and such should not be set in dealloc. Dealloc might not get called when you think it will. You should set such operations inside viewWillDissapear or viewWillUnload.
Upvotes: 7