Suppose I have a model, Car, that is instantiated in ViewModel1 with the following initial properties:
ViewModel1
let car = Car(make: "McLaren", model: "P1", year: 2015)
Then I require additional information of the car to be completed in the next view controller. What is the correct way to pass a model between view controllers when following MVVM?
Using MVC, it is simple to do since the view can have reference to the model:
vc2.car = car
Below is a pseudo attempt at the problem, however I am under the impression that a view model should be private and only accessible to a single view controller. Therefore, the below attempt seems incorrect to me.
ViewController1
fileprivate let viewModel = ViewModel1()
func someMethod() -> {
let car = self.viewModel.car
let vc2 = ViewController2()
vc2.viewModel.car = car
present(vc2, animated: true, completion: nil)
}
ViewController2
let viewModel = ViewModel2()
func anotherMethod() {
print(self.viewModel.car.make) //prints "McLaren"
viewModel.manipulateCar() //adds additional information to the car object
print(self.viewModel.car.color) //prints "Black"
//Pass the finished car to the last view controller to display a summary
let vc3 = ViewController3()
vc3.viewModel.car = self.viewModel.car
}
I am wondering if what I have shown above is a fine way of doing things when using MVVM, or if not, what is the best way to pass the car between view controllers?
EDIT
This question does not have to do with Class vs Struct. The MVC example above implied it is going to be a class (since it is a reference) and it is being passed between multiple view controllers to complete more parts of the object.
It is a question of how to pass models between view controllers when following MVVM and whether view models should be private to the view controller.
With MVVM, the view controller should not reference the model, therefore should not have a variable var car: Car?
. Therefore, you should not see:
let vc2 = ViewController2()
vc2.car = car
Would it be incorrect to see this?
let vc2 = ViewController2()
vc2.viewModel.car = car
See Question&Answers more detail:
os