在MVVM模式中使用闭包将视图模型与视图控制器绑定是一种好的做法吗



我有一个应用程序,在该应用程序中,长按单元格会将其从集合视图中删除。删除发生在视图模型中,看起来如下:

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是个好主意?

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

相关内容

最新更新