skip to Main Content

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


  1. Chosen as BEST ANSWER

    this is now my solution. I hope it is like practice. I look forward to your comments.

    //Gewicht summieren
    func printData() {
        //Shorthand Argument Names
        let request: NSFetchRequest<Gegenstand> = Gegenstand.fetchRequest()
        request.returnsObjectsAsFaults = false
        request.predicate = NSPredicate(format: "eingepackt = true")
        
        do {
            let gesamtListe = try context.fetch(request)
            let sum = gesamtListe.reduce(0) { $0 + ($1.value(forKey: "gewicht") as? Double ?? 0) }
                            print("Gesamtgewicht: (sum) kg")
                            //gewicht = sum
                            if sum > 3500 {
                                gewichtLabel.textColor = .red
                                gewichtLabel.text = "(sum) kg"
                            } else {
                                gewichtLabel.textColor = .black
                                gewichtLabel.text = "(sum) kg"
                            }
        
        } catch {
            print("Gesamtgewicht konnte nicht berechnet werden.")
        }
        
    }
    

  2. Create a coreData fetchRequest with isValue=true,

    Calculate the sum of return fetchRequest

    func fetchAllWithTrue() -> [Gegenstand] {
                    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: Gegenstand)
                    fetchRequest.predicate = NSPredicate(format: “isValue== YES")
                    do {
                        let fetchedObjects = try coreDataManager.context.fetch(fetchRequest) as? [Gegenstand]
                        return fetchedObjects
                    } catch {
                        print(error.localizedDescription)
                        return [Gegenstand]()
                    }
                }
    
    Login or Signup to reply.
  3. You can do all of it in Core Data if you want. Filter for true filtering with an NSPredicate, and have Core Data calculate the sum using NSExpression.

    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 it flag. Put your property name there):

    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Gegenstand")
    fetchRequest.resultType = .dictionaryResultType
    fetchRequest.predicate = NSPredicate(format: "flag = true")
    

    Then set up an NSExpressionDescription that can get the sum of gewicht values:

    let sumExpression = NSExpression(format: "sum:(gewicht)")
    let sumExpressionDescription = NSExpressionDescription()
    sumExpressionDescription.expression = sumExpression
    sumExpressionDescription.resultType = .double
    sumExpressionDescription.name = "gewichtSum"
    

    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 named gewichtSum. Fetch requests know how to use that kind of property. You do it like this:

    fetchRequest.propertiesToFetch = [ sumExpressionDescription ]
    

    Since the fetch uses dictionaryResultType, running the fetch returns an array of dictionaries. It’s an array because fetch always returns an array, but here there’s only one entry. The dictionary in that array entry has a key called gewichtSum for a Double property that was calculated from the expression above. You get the value like this:

    do {
        let result = try context.fetch(fetchRequest)
        if result.count > 0,
            let sumInfo = result[0] as? [String:Double],
            let gewichtSum: Double = sumInfo["gewichtSum"] {
            print("Sum: (gewichtSum)")
        }
    } catch {
        ...
    }
    

    The print statement above prints the sum of all gewicht values where flag is true. It only includes true values for flag because of the NSPredicate, and it contains the sum because of the expression description.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search