假设我有三个实体。 人: 姓名 地址 (对多工资)和(对多贷款)
工资: 收入 税 相对:(对一个人)
账单 数量 相对:(对一个人)
如何执行具有如下结果的提取:
John Doe, SUM>收入, SUM>金额 Eva Doe,SUM>收入,SUM>金额
使用 swift
最佳答案
使用键值编码“集合运算符”(参见 here )而不是获取,这可能最容易完成。对于每个人
:
let name = person.name
let totalIncome = person.valueForKeyPath("salary.@sum.income")
let totalLoans = person.valueForKeyPath("loans.@sum.amount")
如果性能是一个问题,您可以通过修改获取请求(针对 Person 对象)以“预获取”相关的 Salary
和 Bills
对象来改进:
fetchRequest.relationshipKeyPathsForPrefetching = ["salary", "loans"]
或者,可以在一次提取中检索所有所需信息,但我不推荐这样做,因为它需要更改 fetchRequest 以返回字典数组而不是 NSManagedObjects
数组。这使得后续处理(例如填充您的 TableView )更加困难。
// Define NSExpression and NSExpressionDescription for the total income
let incomeED = NSExpressionDescription()
incomeED.expression = NSExpression(forKeyPath: "salary.@sum.income")
incomeED.name = "totalIncome"
incomeED.expressionResultType = .Integer64AttributeType
// Define NSExpression and NSExpressionDescription for the total amount
let amtED = NSExpressionDescription()
amtED.expression = NSExpression(forKeyPath: "loans.@sum.amount")
amtED.name = "totalLoans"
amtED.expressionResultType = .Integer64AttributeType
// specify attributes and expressions to fetch
fetchRequest.propertiesToFetch = ["name", incomeED, amtED]
// specify dictionary return type (required to process NSExpressions)
fetchRequest.resultType = .DictionaryResultType
获取的结果将是一个字典数组;每个字典都有键“name”、“totalIncome”和“totalLoans”(具有相应的值)。
关于swift - 从核心数据中获取子总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556561/