SickAustrian SickAustrian - 1 month ago 9
Swift Question

When to use init() when creating UIViewController?

In the past I always used

viewDidLoad
to initialise my
ViewControllers
, mostly to perform additional initialization on views as it is suggested by
Apple's
documentation. Sometimes however, I also
initialise
model objects in the
viewDidLoad
that help me to do a certain task. Here is an example code:

override fun viewDidLoad()
{
super.viewDidLoad()

// Initialisation of my views
self.label.text = "text"
self.imageView.image = UIImage( named: "image" )
etc.
.
.

// Initialisation of my models
self.videoRecorder = VideoRecorder()
etc.
.
.
}


When I think about it now, doesn't it make more sense to put model initialisation the
init
method of the
ViewController
?

I apologise in advance if my question seems obvious, however I found that in most
iOS
tutorials I have seen, people tend to only perform
initialisation
in the
viewDidLoad
method.

Many thanks for your help in advance.

Answer

The reason people usually do not do this is because view controllers often get instantiated from storyboards and xib files. When that is the case, the normal init is not called. Instead initiWithCoder: is used and then any properties marked with IBOutlet are set accordingly.

Note that this very often makes initializing properties redundant, as they tend to be set via IBOutlet as well.

So if you want your view controller to properly work also when just using it with init, ensure you won't have troubles when it's used from a storyboard (unless you're absolutely certain that will never happen), you would most likely have to implement both, init and initWithCoder:. I have seen a lot of people running into problems because they expected a property set in init to be there in viewDidLoad (when loading the controller from a storyboard).

Because of all this, most programmers don't bother about init and rely on viewDidLoad, because that is definitely called at some point. Writing a proper "both ways usable" controller is just more code.

Comments