我正在考虑用于测试应用程序的非常简单的 ViewModel 和 ViewController 的结构。我有类似于:
FirstViewController.m:
- (IBAction)launchButtonSelected:(id)sender
{
[self.viewModel launchActionSelected];
}
FirstViewModel.m:
- (void)launchActionSelected
{
// [todo] - Figure this out.
}
当 FirstViewController
中的 launchButton
被选中时,我想创建并显示一个 SecondViewController
。
我的问题:
- 对于我应该在哪里创建
SecondViewController
的 ViewModel 是否有可靠的经验法则? - 谁应该初始化
SecondViewController
? - 我应该将
SecondViewController
推到 View 层次结构的什么地方? (即导航推送或模态呈现)。
我个人认为:
SecondViewController
的 ViewModel 可能会在其初始化程序中创建。这总是让我走上一条令人困惑的道路:如果我想将信息从FirstViewModel
传递到SecondViewModel
怎么办?我是否应该将SecondViewModel
公开为SecondViewController
上的公共(public)属性,以便我可以在其上获取/设置值?FirstViewController
应该创建SecondViewController
,并且FirstViewController
应该将SecondViewController
推送到屏幕上。
我的直觉认为这是次要的:我想更多地隔离 ViewController 的表示,并让应用程序更加专注于 ViewModel,但这似乎很难做到。 (即“推送”ViewModels,而不是 ViewControllers……但“推送”本质上与应用程序的视觉呈现相关,所以这可能是错误的思考方式。)
最佳答案
很好的问题。重要的是要记住,无论如何在 iOS 上,MVVM 是一种新兴的范例,具有新兴的最佳实践。因此,对于您关于硬性规定的第一个问题的答案是,实际上并没有任何规定。我个人会在 FirstViewController
的 View 模型中创建 SecondViewController
的 View 模型,这样它就可以在将要使用的上下文中进行配置(即:如果新的 View Controller 被推送以响应 TableView 选择,索引路径)。您对其他两个问题的回答是正确的,至少在我对 iOS 上的 MVVM 的解释中是这样。
View 模型不应该访问您的 View ,并且由于 MVVM 将 View 和 View Controller 形式化为一个单元,因此它们也不应该创建或推送 View Controller 。希望这是有道理的。
我在 GitHub 上编写了一个使用 MVVM 的应用程序。你可以看看here .
关于ios - MVVM 并推送 ViewController : where to initialize the next ViewController and ViewModel, 并推送新 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21922348/