【问题标题】:Is a good practice bind view model with view controller using closure in MVVM pattern?使用 MVVM 模式中的闭包将视图模型与视图控制器绑定是一种好的做法吗?
【发布时间】:2018-12-07 19:01:01
【问题描述】:

我有一个应用程序,在该应用程序中,长按后会从集合视图中删除单元格。删除发生在视图模型中,它看起来像这样:

func deleteFood(forIndexPath indexPath: IndexPath, completion: @escaping ([FoodBySections], [FoodBySections]) -> ()) {
    let objectToDeleteName = self.foodBySections[indexPath.section][indexPath.row].name!

    let oldData = foodBySections
    CoreDataHelper.sharedInstance.deleteFoodFromFridge(foodName: objectToDeleteName)
    foods = CoreDataHelper.sharedInstance.fetchFoods()
    //newData
    foodBySections = FoodBySections.split(foods: foods!)
    //return data to view controller for collection view
    completion(oldData, foodBySections)
}

在视图控制器中代码如下所示:

 @objc func deleteFood(gesture: UILongPressGestureRecognizer!) {
    if gesture.state != .ended {
        return
    }

    let point = gesture.location(in: self.collectionView)

    if let indexPath = self.collectionView?.indexPathForItem(at: point) {
        self.foodViewModel?.deleteFood(forIndexPath: indexPath, completion: { [weak self] (oldData, newData) in
            guard let self = self else { return }
            //receive data from view model via closure
            self.collectionView.animateItemAndSectionChanges(oldData: oldData, newData: newData)
        })
    }
}

这是一个好习惯吗?还是 RxSwift 是个好主意?

【问题讨论】:

    标签: ios swift mvvm closures


    【解决方案1】:

    只要您将视图与对实际视图不做任何事情的数据源和后台函数分开,就应该没问题,这是一种很好的做法。在您的情况下,我不确定您将函数放置在哪里,但我猜测该操作会一直传播到 viewModel,然后传播到 dataSource 以删除该项目。我已经使用 MVVM 构建了一些应用程序,它真的很棒、干净且易于理解。我的上一个应用程序使用的是响应式的,不完全是 RxSwift 而是 ReactiveSwift,无论如何它们几乎相同。老实说,如果您有时间和耐心将您的应用程序重写为 rx,这绝对是一个好主意,它确实为我节省了很多委托和观察的时间,但一开始掌握起来有点复杂。

    【讨论】:

    • 谢谢!我将用于与 Core Data 交互的函数放在类 CoreDataHelper: NSObject 中。使用此类查看模型以更改 Core Data 中的数据。在我的问题中,这段代码是 CoreDataHelper.sharedInstance.deleteFoodFromFridge()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 2011-08-25
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    相关资源
    最近更新 更多