SickAustrian SickAustrian - 5 months ago 30
Swift Question

When to use init() when creating UIViewController?

In the past I always used

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

override fun viewDidLoad()

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

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

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

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

Many thanks for your help in advance.


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.