Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data to UIViewController under MVVM pattern

Tags:

ios

mvvm

I'm using MVVM for my view controllers and I'm facing an issue that I'm not really sure what would be the best way to solve it. Basically, view controller A shows a table view which is populated with data from view model A. Each cell has its own view model. View model A is responsible for creating these view models and expose them to the view controller. But now that I select one of these items I found that my models (the data I need to pass to the other view controller so it can create its own view model off that data) are hidden behind the view models. View models shouldn't expose the model, but then how could I pass this data to the other view controller? Should the cell view model also expose everything that is needed by the other view controller and just pass that view model? That doesn't seem right either.

like image 448
mdonati Avatar asked Aug 02 '17 14:08

mdonati


2 Answers

After evaluating and playing around with suggestions listed in this post, I decided to go with an approach where the view model of view controller A is responsible for creating the view model of view controller B, considering that it is the one having the data. I got the approach from http://www.martinrichter.net/blog/2015/08/20/navigation-with-mvvm-on-ios/ and I think is the best way to not break MVVM abstraction.

like image 94
mdonati Avatar answered Nov 14 '22 19:11

mdonati


I would strongly suggest using protocols for passing data. You could set the view-controller which is to receive the data as the delegate of the view-controller from which the data would be sent. Delegation is a very widely used pattern in the iOS since much of the architecture of the iOS itself is designed around that.

Let me know if you need help or would like to see some code which accomplishes this.

like image 35
userx Avatar answered Nov 14 '22 19:11

userx