Parijat Kalia
Parijat Kalia

Reputation: 5085

Initializing View Controller variables?

This to me is a naive question, but I have some variables in my View Controller which I am not sure where I should be initializing them. I mean, if this was a custom class, then typically I would initialize and give them values in the init method or a custom initWith method.

Further questions that stem from the above are:

Where is the init method for a View Controller. And also, since the View Controller is essentially a class and must be alloc-init at some place. Where exactly is the instance of View Controller being created?

Thanks much,

Parijat Kalia

Upvotes: 1

Views: 2780

Answers (1)

aleph_null
aleph_null

Reputation: 5786

Initializing variables in the right place is very important for a view controller. There are four places in which you can do so:

1) initWithNibName:bundle: This is really the constructor of the view controller. The call [[MyViewController alloc] init] actually ends up calling [[MyViewController alloc] initWithNibName:nil bundle:nil], which indicates you're using a default nib name.

2) awakeFromNib When instantiating a view controller entirely from a nib, initWithNibName:bundle: isn't called since you're not creating a new ViewController but rather deserializing an existing one. In this case, awakeFromNib gets called after deserialization.

initWithNibName:bundle and awakeFromNib are good places to initialize variables that only get created once throughout your view controller's lifecycle and are not related to any views I like to initialize these variables in a function called "setup" and call [self setup] from both initWithNibName:bundle and awakeFromNib.

3) viewDidLoad Called when the view has been loaded. Good place to initialize stuff related to your views.

4) viewWillAppear:animated Called when the view is about to become visible. The dimensions (i.e. bounds, frame, position...) of the subviews are only available as of this function, so you want to initialize variables that depend on these quantities here, not in either of the above methods.

Upvotes: 7

Related Questions