I have a tableview with values. The database is made with core data. You can set the values to true or false. I only want to sum the values with true. To sum the values i have this code.
func printData() {
//Shorthand Argument Names
//let request: NSFetchRequest<Gegenstand> = Gegenstand.fetchRequest()
//let records = try! context.fetch(request) as [NSManagedObject]
let sum = ViewController.liste.reduce(0) { $0 + ($1.value(forKey: "gewicht") as? Double ?? 0) }
print("Gesamtgewicht: (sum) kg")
gewicht = sum
if gewicht > 3500 {
gewichtLabel.textColor = .red
gewichtLabel.text = "(gewicht) kg"
}
}
I tried it with an if-function but i don’t know to use it with core data.
3
Answers
this is now my solution. I hope it is like practice. I look forward to your comments.
Create a coreData fetchRequest with isValue=true,
Calculate the sum of return fetchRequest
You can do all of it in Core Data if you want. Filter for
true
filtering with anNSPredicate
, and have Core Data calculate the sum usingNSExpression
.First set up the fetch request to get only entries where the property is
true
and make sure it returns dictionary-type results (I don’t know what your boolean is called, so here I’m calling itflag
. Put your property name there):Then set up an
NSExpressionDescription
that can get the sum ofgewicht
values:What this does is create a new kind of property that Core Data understands where the value is the sum the values of
gewicht
and is namedgewichtSum
. Fetch requests know how to use that kind of property. You do it like this:Since the fetch uses
dictionaryResultType
, running the fetch returns an array of dictionaries. It’s an array becausefetch
always returns an array, but here there’s only one entry. The dictionary in that array entry has a key calledgewichtSum
for aDouble
property that was calculated from the expression above. You get the value like this:The
print
statement above prints the sum of allgewicht
values whereflag
is true. It only includes true values forflag
because of theNSPredicate
, and it contains the sum because of the expression description.