7

I am trying to initialise a UIViewController in my Swift application but I am facing a problem to which I cannot find any definitive answer.

I would like to call this from a FlowCoordinator to initialise the controller, but my initialiser requires a NSCoder object due to the required init?(coder: NSCoder) function.


MyAwesomeController()

Is there a way to initialise differently the controller, without the need to pass the NSCoder object?

If there is not, how can I create such an object in a way to avoid the following exception:

'NSInvalidArgumentException', reason: '*** -decodeObjectForKey: cannot be sent to an abstract object of class NSCoder: Create a concrete instance!'

Thank you very much in advance

4
  • You can create an additional initializer. Commented May 11, 2019 at 12:07
  • You might want to read this: programmingios.net/dont-make-a-new-instance-by-mistake-2 Commented May 11, 2019 at 12:34
  • Thank you @matt, you solved my problem, I didn't get before that I was creating a new controller, not the one I had already linked to the storyboard. Commented May 11, 2019 at 14:26
  • You are welcome! Those articles are meant to help with common problems like this. So I'm very happy if I helped you "get" this concept. Commented May 11, 2019 at 14:27

2 Answers 2

11

Use something like this, I included a property also as a demo:

class MyAwesomeViewController: UIViewController {
    let someInt: Int

    init(someInt: Int) {
        self.someInt = someInt

        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("Storyboard are a pain")
    }
}

I like creating everything programmatically.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried this method but it launches the fatalError because I am not providing the NSCoder object when I create the Controller in the FlowCoordinator. Thanks for the answer!
2

Since UIViewController inherits feom UIResponder, and UIResponder inherits from NSObject, it has empty initializer like init(). So you can just call MyAwesomeController() and it works without any errors. If there is any the error is somewhere else like an outlet in storyboard.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.