0

In the entity Shift I have two attributes startTime and endTime, I want to take the difference and then sum over all fetched values.

let fetchRequest = NSFetchRequest<NSDictionary>(entityName: "Shift")
        fetchRequest.predicate = shiftPredicate
        fetchRequest.resultType = .dictionaryResultType

        let durationExpression = NSExpressionDescription()
        durationExpression.name = "duration"
        durationExpression.expression = NSExpression(format: "endTime - startTime")
        durationExpression.expressionResultType = .integer16AttributeType

// INSERT A

 do { let result = try
            managedObjectContext.fetch(fetchRequest)
            print("\(result)")
            let resultDict = result.first
            print("\(String(describing: resultDict?["sumDuration"]))")

        } catch let error as NSError {
            print ("Could not fetch \(error), \(error.userInfo)")
        }

Now this fetch returns an array of dictionaries containing [{duration, 3}, {duration, 6}] But I want to sum over all the duration values.

I have tried the following at INSERT A

       let sumDurationExpression = NSExpressionDescription()
        sumDurationExpression.name = "sumDuration"
        sumDurationExpression.expression = NSExpression(forFunction: "sum:", arguments: ["duration"])
        sumDurationExpression.expressionResultType = .integer16AttributeType
        fetchRequest.propertiesToFetch!.append(sumDurationExpression)

But this crashes with unrecognized selector sent, i have also tried

        durationExpression.expression = NSExpression(format: "sum: (endTime - startTime")
Richard Legault
  • 443
  • 4
  • 9
  • Apparently `@sum` can only be used with a key path, not with general expressions (like your difference). Compare https://stackoverflow.com/q/14122086/1187415 for a similar issue. The workaround is to fetch the differences, and then add the differences from the fetched array. – Martin R Jun 20 '19 at 07:18
  • ... or fetch the sum of endTime, and the sum of startTime (two NSExpressions, all in one fetch), and subtract the two. – pbasdf Jun 20 '19 at 07:34

0 Answers0