0

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)
    }
}
Mike Haslam
  • 245
  • 3
  • 21

2 Answers2

1

Use NSBatchUpdateRequest

func resetAllSubtotals(){
    let request = NSBatchUpdateRequest(entityName: "WindowCounter")
    request.propertiesToUpdate = ["qty":0]
    request.resultType = .updatedObjectsCountResultType
    
    do {
        let result = try context.execute(request) as! NSBatchUpdateResult
        //This print the number of rows affected/updated
        print(result.result!)
    }catch {
        //Handel Catch here
    }
}

Raja Kishan
  • 16,767
  • 2
  • 26
  • 52
0

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

 extension NSManagedObjectContext {
  
  func resetAllSubtotals(){
   let allCounters: NSFetchRequest<WindowCounter> = 
   WindowCounter.fetchRequest()

   do {
       let savedWindowCounters = try self.fetch(allCounters)

       for counter in savedWindowCounters {
           counter.qty = 0
           counter.subtotal = 0
       }
       try self.save()
   } catch {
       print(error.localizedDescription)
   }

} }

Mike Haslam
  • 245
  • 3
  • 21