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

How to persist a computed property SwiftUI 2.0 Xcode 12.3

Forums > SwiftUI

Hey Groovy Guys & Gals! I hope all is well?

I need help with. How to update a computed property to Core Data SwiftUI 2.0 Xcode 12.3

I am trying to update and persist subtotal in my app when user increments using a stepper

Current App flow

User enters data in form data gets saved to core data.

an @FetchRequest get the data from core data.

In a list the core data entities are iterated over and data is passed to a view

In the view a computed property gets and updates the subtotal locally in view only.

The user by tapping a stepper can increment or decrement and subtotal gets displayed localy only

Question: How to constantly update subtotal and persist so I can access in another view to total all subtotals and reset each instance of the subtotal

Here is what I tried

import SwiftUI

struct testView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(entity: WindowCounter.entity(), sortDescriptors: [

        NSSortDescriptor(
            keyPath: \WindowCounter.userOrder,
            ascending: true),
        NSSortDescriptor(
            keyPath:\WindowCounter.subtotal,
            ascending: true )
    ]) var windows: FetchedResults<WindowCounter>
    @Environment(\.colorScheme) var colorScheme
    @ObservedObject var estimatorData: EstimatorViewModel

    var id: UUID
    @State var price: Double
    @State var qty: Int
    @State var subtotal: Double

    var getSubtotal: String {
        let result = (Double(qty) * price)
        return String(format: " %.2f", result)
    }

    var body: some View {
        VStack {
            //.....
            HStack {
                // ....
                Text("Subtotal $ \(getSubtotal)")
                    .foregroundColor(Color("Primary"))
                    .onChange(of: getSubtotal) { newValue in
                        updateSubtotal(newSubTotal: getSubtotal)
                    }
                //....
            }

        }
    }

   // After more reasearch this is probably the wrong approach 
   // as this get updated quite Often

    func updateSubtotal(newSubTotal: String) {

        for window in windows {
            window.subtotal = Double(newSubTotal) ?? 0.00
        }
        do {
            try viewContext.save()
        }
        catch {
            print(error.localizedDescription)
        }
    }
}

3      

If what you're saying is that the subTotal should always be saved to CoreData? Then this, to me, is a bound property with which you will trigger some calculation against to produce it's value.

What is it that isn't working? (it's early and before coffee).. but I don't see anything broken, per se. If you want to pass that subtotal around, if it's saved in your ObservedObject that shouldn't be an issue. Similarly, if it's just stored in State .. well you can pass it via a Binding on a child view.

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.