Andi
Andi

Reputation: 9034

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.

Upvotes: 1

Views: 804

Answers (3)

Vui Nguyen
Vui Nguyen

Reputation: 21

If you're initializing viewController variables using data passed in from a segue, then it works better (from my personal experience) to do it in viewDidLoad instead of init. When I tried to initialize from init, the viewController did not get the values passed in from the segue.

Upvotes: 0

Gero
Gero

Reputation: 4424

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.

Upvotes: 3

Max Pevsner
Max Pevsner

Reputation: 4104

In general it is not advised to perform tasks in a constructor (init()). However creating an object which is a property of a ViewController can be considered a simple initialization, so it looks OK to do it in the init().

Each case should be considered separately depending on the nature of the model you create and its responsibilities.

The thumb rule is: performing tasks - no, initializing properties - yes.

Upvotes: 0

Related Questions