Is it possible for a fatalError in the required init? (Coder aDecoder: NSCoder) when am I not using storyboards?

I have ViewController

one that needs to be initialized with ViewModel: NSObject

.

My implementation ViewController

:

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 a simple override init

:

class ViewModel: NSObject {

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

}

      

I understand that I need an implementation required init?(coder aDecoder: NSCoder)

in ViewController

as it follows the protocol NSCoding

. But I'm not sure what is safe to have fatalError

.

When I change fatalError

to super.init(coder: aDecoder)

, I get

Self.viewModel property not initialized when calling super.init

I don't want to make an ViewModel

optional variable because there cannot be in my application logic 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 as ViewModel

it is not the only constant that needs to be implemented on initialization ViewController

.

So my questions are:

  • Is it safe to have fatalError

    in this method init

    ?
  • I am not using storyboards in my application (only for the launch screen). Can I be sure this method init?(coder...

    won't work anyway?
  • Or maybe there is an option to record it without fatalError

    ?
  • Or do I need a full implementation in it because in some cases my application will use it?

Thanks for any help!

+3


source to share


2 answers


Since you are not using a storyboard, you can disable your init, so you cannot use it in your code:



@available(*, unavailable) required init?(coder aDecoder: NSCoder) {
    fatalError("disabled init")
}

      

+5


source


You have a nice start here with dependency injection if you want to make it easier to write tests for it later with mocked data.

ViewController:

class ViewController: UIViewController {

    let viewModel = ViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel.runFunction()
    }
}

      



ViewModel:

class ViewModel: NSObject {

    var networkingService: NetworkingService?

    init(withNetworkingService networkingService: NetworkingService = null) {
        self.networkingService = networkingService
    }
}

      

+1


source







All Articles