UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SwiftUI 2.0 Xcode 12 How To Update A Single Attribute Of A Core Data Entity

Forums > SwiftUI

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)
    }
}

My Solution is I decided not to Observe object in 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)
       }
   }
}

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.