如何按小时对CoreData结果进行分组,并使用swift对其总数进行求和?

时间:2016-06-12 04:14:28

标签: ios swift core-data group-by

我有一个存储在CoreData中的步骤数据,它有一个如下所示的实体:

-Attribute-    -Type-
  steps        Double
  date         Date

我想检索当天每小时的总步数。 到目前为止,我的查询看起来像这样:

        let activityFetch = NSFetchRequest(entityName: "Steps")
        activityFetch.resultType = .DictionaryResultType

        let hourInDay = NSExpressionDescription()
        hourInDay.name = "hourInDay"
        hourInDay.expression = NSExpression(format: "FUNCTION(date,'hourInDay')")
        hourInDay.expressionResultType = .Integer16AttributeType

        let sumSteps = NSExpressionDescription()
        sumSteps.name = "sumOfSteps"
        sumSteps.expression = NSExpression(format: "sum:(steps)")
        sumSteps.expressionResultType = .DoubleAttributeType

        activityFetch.propertiesToFetch = [sumSteps, hourInDay]
        activityFetch.propertiesToGroudpBy = [hourInDay]

        var activityResults:NSArray = []
        do {
            //Success
            activityResults = try context.executeFetchRequest(activityFetch)
            for result in activityResults{
                print("  Result: \(result)")
            }
        } catch let error as NSError {
            //Failure
            print ("   fetch Activities failed: \(error.localizedDescription)")
        }

我正在使用一个帮助函数返回每个时间戳的小时:

func hourInDay(date:NSDate) -> Int{
    return NSCalendar.currentCalendar().component(.Hour, fromDate: date)
}

当我运行该函数时,我当前收到一个NSInvalidArgumentExecption:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid keypath expression ((<NSExpressionDescription: 0x129337160>), name hourInDay, isOptional 1, isTransient 0, entity (null), renamingIdentifier hourInDay, validation predicates (
), warnings (
), versionHashModifier (null)
 userInfo {
}) passed to setPropertiesToFetch:'

有什么想法吗?

0 个答案:

没有答案