Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to have fatalError in required init?(coder aDecoder: NSCoder) when I don't use Storyboards?

I have a ViewController, which need to be initialized with ViewModel: NSObject.

My implementation of ViewController is:

class ViewController: UIViewController {

    let viewModel: ViewModel

    init(withViewModel viewModel: ViewModel) {
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

ViewModel has simple override init:

class ViewModel: NSObject {

    override init() {
        super.init()
        // Some other logic
    }

}

I understand, that I need required init?(coder aDecoder: NSCoder) in ViewController implementation since it conforms NSCoding protocol. But I'm not sure if it is safe to have fatalError there.

When I change fatalError to super.init(coder: aDecoder) I receive

property 'self.viewModel' not initialized at super.init call

I don't want to make viewModel an optional variable, because in my App logic it can't be nil.

Also, when I change init?(coder... to

required init?(coder aDecoder: NSCoder) {
    self.viewModel = ViewModel()
    super.init(coder: aDecoder)
}

this also doesn't satisfy me, since viewModel isn't the only constant, which need to be implemented during initialization of ViewController.

So, my questions:

  • Is it safe to have fatalError in this init method?
  • I don't use Storyboards in my App (only for Launch Screen). Can I be sure, that this init?(coder... method won't run in any case?
  • Or maybe there is an option to write it without fatalError?
  • Or do I need a full implementation in it, because in some cases my App will use it?

Thanks for any help!

like image 417
Peter Tretyakov Avatar asked May 11 '17 16:05

Peter Tretyakov


1 Answers

Since you don't use storyboard you can disable your init, so you won't be able to use it in code:

@available(*, unavailable) required init?(coder aDecoder: NSCoder) {
    fatalError("disabled init")
}
like image 134
Vasilii Muravev Avatar answered Oct 11 '22 14:10

Vasilii Muravev