Refresh values in a view that displays the sum of an attribute from CoreData in SwiftUI

40 Views Asked by At

I am working on a personal app to help me log income and calculate tax etc

I have a view that displays the totals and does a little math to calculate tax and profits etc. To get the sum values I use the following function:

func sumRevenue() -> Double {
var revenueTotal : Double = 0.00

let expression = NSExpressionDescription()
expression.expression =  NSExpression(forFunction: "sum:", arguments:[NSExpression(forKeyPath: "revenue")])
expression.name = "revenueTotal";
expression.expressionResultType = NSAttributeType.doubleAttributeType

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Log")
fetchRequest.propertiesToFetch = [expression]
fetchRequest.resultType = NSFetchRequestResultType.dictionaryResultType

do {
    let results = try managedObjectContext.fetch(fetchRequest)
    let resultMap = results[0] as! [String:Double]
    revenueTotal = resultMap["revenueTotal"]!
} catch let error as NSError {
    NSLog("Error when summing amounts: \(error.localizedDescription)")
}

return revenueTotal
}

In my CoreData model, "Log" is the entity and in this case, "revenue" would be the attribute. All works well and the totals display in the TotalsView by using "sumRevenue", however the totals don't update in that View when I add a new log, but they are added to the list of logs just fine and do update if I rebuild.

I know the answer probably has something to do with ObservedObject but I am new to all this and I am struggling with it. Any advice would be much appreciated.

0

There are 0 best solutions below