8

I've been trying to understand for hours when I should use the viewDidload: and when I should use initWithNibName: to set up the properties of my viewController.

For instance, I'm using a TableViewController and I'm setting all its properties (such as the backgroundColor, the separateColor, the toolbar items) in initWithNibName. It is the right way to do ?

If somebody could enlighten me.

Thanks

Titouan de Bailleul
  • 12,920
  • 11
  • 66
  • 121

3 Answers3

12

You should set up your properties in the viewDidLoad. This method is called by the system when the controller's view is loaded into memory. The initWithNibName: is something that you call when you create a controller instance from a nib file.

That is to say, that if you set up your properties in the initWithNibName: and instead you call init, your controller might not be in a good state; thus, it's best to do in viewDidLoad.

Jeremy
  • 8,902
  • 2
  • 36
  • 44
  • 2
    Also note that viewDidLoad (and all the other delegate methods) are called at various points of the application's life. Such as when the app is awaken from a background state, or when the app is closed etc. For this reason, you should always be setting up your view within these delegate methods. – Daryl Teo Jan 04 '12 at 23:14
  • Thanks, I'm starting to understand a bit better what I do now. And thanks Daryl for precisions about the application's life – Titouan de Bailleul Jan 04 '12 at 23:21
  • Note that there is one exception to this rule of thumb, for tab view controllers, you want to set up the title and icon of the tab in the initWithNibName, otherwise those won't be set until you tap on that specific tab – JP Hribovsek Dec 07 '12 at 06:44
3

You should use viewDidLoad: method of your controller. To quote from Apple's documentation on initWithNib:

The nib file you specify is not loaded right away. It is loaded the first time the view controller’s view is accessed. If you want to perform additional initialization after the nib file is loaded, override the viewDidLoad method and perform your tasks there.

Ryan Crews
  • 3,015
  • 1
  • 32
  • 28
3

initWithNibName: is called when the NIB is loaded and instantiated.

viewDidLoad: is called when your view is actually presented onscreen.

And yes - I believe that in your case, setting colors and such are best done in initWithNibName

Fletch
  • 963
  • 6
  • 15