I'm thinking through the structure of a very simple ViewModel and ViewController for a test application. I have something akin to:
FirstViewController.m:
- (IBAction)launchButtonSelected:(id)sender
{
[self.viewModel launchActionSelected];
}
FirstViewModel.m:
- (void)launchActionSelected
{
// [todo] - Figure this out.
}
When the launchButton
is selected in the FirstViewController
, I want to make and present a SecondViewController
.
My questions:
SecondViewController
's ViewModel?SecondViewController
?SecondViewController
onto the view hierarchy? (i.e. a navigation push or a modal presentation).I was personally thinking:
SecondViewController
will probably be created in its initializer. This always leads me down a confusing path: what if I want to pass information from FirstViewModel
to SecondViewModel
? Should I expose SecondViewModel
as a public property on SecondViewController
so I can get/set values on it?FirstViewController
should create SecondViewController
, andFirstViewController
should push SecondViewController
onto the screen.My intuition considers this to be subpar: I'd like to isolate the presentation of ViewControllers a bit more, and have the app be more ViewModel-focused, but this seems difficult to do. (i.e. "push" ViewModels, not ViewControllers… but "push" is intrinsically related to the app's visual presentation, so perhaps that's the wrong way to think about it.)
Great questions. It's important to remember that, on iOS anyway, MVVM is an emerging paradigm with emerging best practices. So the answer to your first question about hard-and-fast rules is that there aren't really any. I personally would create the SecondViewController
's view model in the FirstViewController
's view model so it can be configured in the context that it will be used (i.e.: if the new view controller is being pushed in response to a table view selection, the index path). Your answers to the other two questions are correct, at least in my interpretation of MVVM on iOS.
View models shouldn't have access to your views, and since MVVM formalizes the view and view controller as one unit, they shouldn't being creating or pushing view controllers, either. Hope that makes sense.
I've got an app I wrote on GitHub that uses MVVM. You can check it out here.