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