hfz
hfz

Reputation: 337

Should I programmatically add subviews in init or ViewDidLoad, and why?

I've been browsing some answers here and I get two different suggestions:

  1. add in init. Example in this answer
  2. add in ViewDidLoad. Suggested in this answer

Which 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

Answers (2)

Mike Weller
Mike Weller

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

Trausti Thor
Trausti Thor

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

Related Questions