在实体 Shift 中,我有两个属性 startTime 和 endTime,我想取差值,然后对所有获取的值求和。
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)")
}
现在这个 fetch 返回一个包含 [{duration, 3}, {duration, 6}] 的字典数组,但我想总结所有的持续时间值。
我在 INSERT A 尝试了以下操作
let sumDurationExpression = NSExpressionDescription()
sumDurationExpression.name = "sumDuration"
sumDurationExpression.expression = NSExpression(forFunction: "sum:", arguments: ["duration"])
sumDurationExpression.expressionResultType = .integer16AttributeType
fetchRequest.propertiesToFetch!.append(sumDurationExpression)
但这会因发送无法识别的选择器而崩溃,我也尝试过
durationExpression.expression = NSExpression(format: "sum: (endTime - startTime")