如何创建访存以总结属性之间的差异

时间:2019-06-20 05:29:52

标签: swift core-data nsexpression

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

现在,此提取操作返回包含[{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")

0 个答案:

没有答案