【发布时间】:2021-01-08 01:47:36
【问题描述】:
我正在使用带有 Coordinator 的 MVVM 来设计应用程序。我怀疑的一件事是如何在不同的ViewModels 之间传递数据。通常,前一个 viewModel 只会创建下一个 viewModel,并且只会在 prepareforsegue 中进行方法依赖注入。但是现在我负责所有导航,我该如何实现呢?
Class AppCoordinator : NSObject, Coordinator, UINavigationControllerDelegate {
var childCoordinators = [Coordinator]()
var navigationController: UINavigationController
var dependencyContainer : MainDependencyContainer
func start() {
let vc = ViewController.instantiate()
vc.coordinator = self
vc.viewModel = dependencyContainer.makeMainViewModel()
navigationController.delegate = self
navigationController.pushViewController(vc, animated: true)
}
func createAccount() {
let vc = CreateAccountViewController.instantiate()
vc.coordinator = self
navigationController.pushViewController(vc, animated: true)
}
}
我当然可以在MainViewModel 中为CreateAccountViewController 创建ViewModel,并在createAccount 方法中将ViewModel 作为参数传递,但在这里这样做是否正确?这里的单元测试意味着什么?
【问题讨论】:
-
据我了解,视图模型应该只是应用程序模型和视图之间的中介。如果应用程序模型是有保证的事实来源,则两个视图模型应该不需要相互了解。
标签: ios swift mvvm dependency-injection coordinator-pattern