I am trying to implement a reset method in my View Model that will be called in a View on button action So the Views will get updated and persisted
Here are the attributes of the entity published in my View Model
var viewContext: NSManagedObjectContext { PersistenceController.shared.container.viewContext }
@Published var price: Double
@Published var qty: Int
@Published var subtotal: Double
Here is my resetAllCounters method I tried I know it’s the wrong approach I just want to reset the qty to 0 and update all the counters
func resetAllSubtotals(){
let allCounters: NSFetchRequest<WindowCounter> = WindowCounter.fetchRequest()
do {
let savedWindowCounters = try self.viewContext.fetch(allCounters)
for counter in savedWindowCounters {
counter.qty = 0
}
try self.viewContext.save()
} catch {
print(error.localizedDescription)
}
}
2
Answers
My Solution is I decided not to Observe object in the view model and instead just observe the entity itself as it conforms to ObservableObject Then made a subclass to handle the method
} }
Use
NSBatchUpdateRequest