MVVM and pushing a ViewController: where to initialize the next ViewController and ViewModel, and push on the new view?

StackOverflow https://stackoverflow.com/questions/21922348

  •  14-10-2022
  •  | 
  •  

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:

  1. Is there a solid rule of thumb for where should I create SecondViewController's ViewModel?
  2. Who should initialize SecondViewController?
  3. Where should I push SecondViewController onto the view hierarchy? (i.e. a navigation push or a modal presentation).

I was personally thinking:

  1. The ViewModel for 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?
  2. FirstViewController should create SecondViewController, and
  3. FirstViewController 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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top