Reputation: 86055
I think we can write init code in the following two places
initwithNibName
viewDidLoad
what the difference.
I think initWithNibName
happens before viewdidLoad
, what's the case we must do some init stuff in the initWithNibName
?
Upvotes: 1
Views: 1025
Reputation: 17014
initWithNibName
would be called first. This is the designated initialiser for UIViewController
; in other words, no matter what other methods you might call to init a UIViewController
, you will end up with a call to initWithNibName
somewhere down the line.
For example, if you just call [[UIViewController alloc] init]
, the default behaviour is to attempt to load a nib file that has the same name as your view controller class.
viewDidLoad
is called later on, after the view has loaded. To quote the API docs:
This method is called after the view controller has loaded its view hierarchy into memory. This method is called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the loadView method. You usually override this method to perform additional initialization on views that were loaded from nib files.
Have have a careful read of the UIViewController
documentation to gain a clearer understanding.
What goes where?
The sort of code that goes into initWithNibName
is the same as for any init
method: usually setting any necessary properties.
As for viewDidLoad
, in here you might put code that needs to be run once the view hierarchy is loaded into memory. For example, if you want to programmatically do something to a UIView
that your controller is responsible for, you do it here, because the UIView wasn't loaded into memory at the time when init
was called.
A common mistake is for people to try to send messages to self.view
(or subviews) in the initWithNibName
method and wonder why it has no effect. It has no effect because self.view
is nil at that point!
Upvotes: 2