Home > Mobile >  Init viewModel in MVVM
Init viewModel in MVVM

Time:11-05

I'm building an app using MVVM. I need to initialize viewModel in my ViewController, and that's how I do it:

 private var viewModel: SunCalendarViewModel!
    
    init(viewModel: SunCalendarViewModel) {
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

However, when I try to call my viewModel, my app crashes because it turns out to be nil:

 func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        viewModel.search(in: textField.text)
        return true
    }

I'm confused, because I believe I do initialize my viewModel in init, so it shouldn't be nil. In MVVM we don't have configurator like in MVP, so I have no ideas where else I should do it. Any help is appreciated!

CodePudding user response:

If you take a look at how clean-swift does it, this could also serve your purpose (enter image description here

Second way is to make the viewmodel property public and initialising it from the parent while instantiating controller, then you don't need the init methods and setup function.

Another way would be over DI

CodePudding user response:

Just based in the code that you've posted, I think maybe you're missing the true initialization of the model that should be something like:

private var viewModel: SunCalendarViewModel!
    
    init(viewModel: SunCalendarViewModel) {
        super.init(nibName: nil, bundle: nil)
        self.viewModel = SunCalendarViewModel()
    }
...
  • Related