Answer the question
In order to leave comments, you need to log in
Data binding in the view model with the controller with RxSwift (MVVM pattern). Is my decision correct?
I want to achieve that my collectionView is updated after deleting data from Core Data. To do this, I have a FoodViewModel with the following content:
class FoodViewModel: FridgeCollectionVIewViewModelType {
public var oldData = Variable<[FoodBySections]>([])
public var foodBySections = Variable<[FoodBySections]>([])
private var foods: [Food]?
//какой-то код
....
//код удаления
func deleteFood(forIndexPath indexPath: IndexPath) {
let objectToDeleteName = self.foodBySections.value[indexPath.section][indexPath.row].name!
oldData.value = foodBySections.value
CoreDataHelper.sharedInstance.deleteFoodFromFridge(foodName: objectToDeleteName)
foods = CoreDataHelper.sharedInstance.fetchFoods()
foodBySections.value = FoodBySections.split(foods: foods!)
}
}
class FridgeCollectionViewController: UICollectionViewController, UIGestureRecognizerDelegate {
@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)
var newData: [FoodBySections]?
_ = self.foodViewModel?.foodBySections.asObservable().subscribe {
newData = $0.element!
}
var oldData: [FoodBySections]?
_ = self.foodViewModel?.oldData.asObservable().subscribe {
oldData = $0.element!
}
self.collectionView.animateItemAndSectionChanges(oldData: oldData!, newData: newData!)
}
}
}
Answer the question
In order to leave comments, you need to log in
To track the state of the CoreData table and update the UI, there is a ready-made convenient solution: NSFetchedResultsController , just delete the required entry from Core Data, and the table will update itself.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question