【问题标题】:How to use NSFetchedResultsController to return total of a relationship property given a predicate如何使用 NSFetchedResultsController 返回给定谓词的关系属性的总数
【发布时间】:2016-09-06 05:29:46
【问题描述】:

我正在编写一个费用跟踪器应用程序,这是我的数据模型:

在一个显示定期(例如每日)费用摘要的屏幕中,我想使用NSFetchedResultsController 来获取所有类别以及它们的总费用每个期间(例如每天)。一个周期由两个NSDate 变量定义——一个startDate 和一个endDate,因为我也会有每周和每月的视图——我认为这应该取决于@987654327 中的摘要索引@。即使总和为零,我也希望 NSFetchedResultsController 返回类别。我不知道如何设置。

我已经尝试过:我已经成功地在我的 Category 实体上构建了一个 NSFetchedResultsController,并使用了一个 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)

我也一直在阅读有关获取属性的信息,但我也找不到在 NSFetchedResultsController 触发获取之前在谓词中指示 startDateendDate 的方法。帮忙?

【问题讨论】:

  • 有使用NSFetchedResultsController的理由吗?我不认为它能够提供你想要的东西(至少,不是没有很多工作)。单个周期(天、周等)可能是可能的,但您需要每个单个周期。您将不得不重建谓词并为每个时期重新执行提取。仅遍历所有费用并计算类别和期间的每个组合的总金额可能会更容易。

标签: ios swift cocoa-touch core-data


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多