如何使用NSFetchedResultsController返回给定谓词的关系属性的总和

时间:2016-05-11 02:21:19

标签: ios swift cocoa-touch core-data

我正在撰写费用跟踪器应用,这是我的数据模型:

enter image description here

在我显示费用周期性(例如每日)摘要的一个屏幕中,我想使用NSFetchedResultsController来获取所有类别以及每个期间的总费用 >(例如每天)。句点由两个NSDate变量定义 - startDateendDate,因为我也会有每周和每月的观看次数 - 我认为应该依赖于NSFetchedResultsController中的摘要。即使总和为零,我也希望NSFetchedResultsController返回类别。我不知道如何设置它。

我尝试过:我已在NSFetchedResultsController实体上成功构建Category并使用NSExpressionDescription获取其expenses的总数关系,但总计所有费用,我无法找到指定包容期的方法。

let request = NSFetchRequest(entityName: Category.entityName)
request.resultType = .DictionaryResultType
request.propertiesToFetch = [
    "name", "color",
    {
        let totalColumn = NSExpressionDescription()
        totalColumn.name = "total"
        totalColumn.expression = NSExpression(format: "@sum.expenses.amount")
        totalColumn.expressionResultType = .DecimalAttributeType
        return totalColumn
    }()
]
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
let fetcher = NSFetchedResultsController(fetchRequest: request, managedObjectContext: App.state.mainQueueContext, sectionNameKeyPath: nil, cacheName: nil)

我也一直在阅读有关已获取属性的内容,但我也无法找到在startDate之前在谓词中指明endDateNSFetchedResultsController的方法解雇了。帮助

1 个答案:

答案 0 :(得分:0)

您可以为获取请求添加谓词:

request.predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", startDate, endDate];