简体   繁体   English

在 MVVM 中的两个 ViewController 之间传递数据

[英]Passing Data Between two ViewControllers in MVVM

I recently started exploring MVVM and stuck at passing data between 2 view controllers.I have an array of items in my viewModel1 of ViewController1 and I want to pass that array to viewcontroller2.我最近开始探索 MVVM 并坚持在 2 个视图控制器之间传递数据。我在 ViewController1 的 viewModel1 中有一组项目,我想将该数组传递给 viewcontroller2。 I am able to achieve it by getting the whole array from viewModel1 like below but I am not sure if this is the right way to do it.我可以通过从 viewModel1 获取整个数组来实现它,如下所示,但我不确定这是否是正确的方法。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == Constants.kShowDetailSegue {
        let destinationViewController = segue.destination as! ListViewController
        destinationViewController.products = viewModel1.getFavouriteProducts()
      //the getFavouriteProducts gets data from coredata.

    }
}

I think you have done it the right way, but alternatively you can use closures.我认为您以正确的方式完成了它,但是您也可以使用闭包。 Which are the preferred, method of communication within iOS.这是 iOS 内首选的通信方法。 You will take care of memory leaks wherever necessary by using您将在必要时使用 memory 泄漏

weak 

OR或者

unowned无主

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM