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