Sandeep Kumar
Sandeep Kumar

Reputation: 1605

viewDidLoad calling before init?

I face a strange situation. In my controller, viewDidLoad is calling before init. Is there any technical reason behind that?

Upvotes: 24

Views: 10332

Answers (6)

Mehdi Ijadnazar
Mehdi Ijadnazar

Reputation: 4951

NOTE for UITabBarController:

I don't know what kind of UIViewController caused this for you but I faced a similar case with UITabBarController. I thought it might help another one facing it with UITabBarController.
As far as I know all viewControllers call init before viewDidLoad, except for the UITabBarController and its subclasses.
As Andrew claims here, UITabBarControllers call loadView inside [super init] method, which causes the call to viewDidLoad. So the viewDidLoad method will be called before init has finished its job.
If you have some thing to setup in viewDidLoad you should perhaps do it inside init method after the call to [super init].

Upvotes: 12

alex-i
alex-i

Reputation: 5454

The viewDidLoad method is being called when accessing self.view inside the init method (since self.view should not yet be loaded from the nib the process seems to be fasten so it doesn't return nil).

Upvotes: 56

I know this is a bit old post, but I'll post my point of view anywhere because I think it could help somebody.

Well, I've been in this same situation. I thought that viewDidLoad was being called before init method in my view controller class. But what was really happening was not that: the flow starts on init method, but jumps to viewDidLoad when calling [super init*], so my log messages in viewDidLoad method were being displayed first that those in my custom initialization.

I think that's it. I hope this to save some time to someone.

[Sorry for my English]

Upvotes: 25

Nick Forge
Nick Forge

Reputation: 21464

When you initialise a UIViewController from code, you use -initWithNibName:bundle:, whereas when it is initialised from a XIB, the XIB loading code will call -initWithCoder:. One, and only one of these two methods will be called, and they will definitely be called before -viewDidLoad.

There's no conceivable way that -viewDidLoad could be called first, unless you are calling it yourself (which you should never really do).

Upvotes: 3

palimpsestor
palimpsestor

Reputation: 1069

If your ViewController is being loaded from your main nib file, then most likely it is initWithCoder that is being called to initialize the controller.

Upvotes: -1

Eiko
Eiko

Reputation: 25632

No, the viewDidLoad message is always called after init.

Are you sure init is called at all? There are several init methods especially for UIViewController, maybe another one is called instead making you think differently.

If you need more information, please paste the code of viewDidLoad and all of your init methods, and tell us how it is loaded (i.e. with code) or from a nib.

Upvotes: 0

Related Questions