从核心数据中获取子总和

Veg*_*Flo 3 core-data nspredicate executefetchrequest swift

假设我有三个实体。 人: 姓名地址(对多工资)和(对多贷款)

薪资: 所得税 Rel:(一对一)

账单 金额Rel:(一对一)

如何执行具有如下结果的提取:

John Doe,SUM>收入,SUM>金额 Eva Doe,SUM>收入,SUM>金额

使用 Swift

pba*_*sdf 5

这可能是使用键值编码“集合运算符”(参见此处)而不是 fetch最容易完成的。对于每个person

let name = person.name
let totalIncome = person.valueForKeyPath("salary.@sum.income")
let totalLoans = person.valueForKeyPath("loans.@sum.amount")
Run Code Online (Sandbox Code Playgroud)

如果性能是一个问题,您可以通过修改获取请求(对于 Person 对象)以“预获取”相关对象SalaryBills对象来改进:

fetchRequest.relationshipKeyPathsForPrefetching = ["salary", "loans"]
Run Code Online (Sandbox Code Playgroud)

或者,也可以在一次 fetch 中检索所有所需信息,但我不建议这样做,因为它需要更改 fetchRequest 以返回字典数组而不是NSManagedObjects. 这使得后续处理(例如填充您的表格视图)更加困难。

// 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
Run Code Online (Sandbox Code Playgroud)

获取的结果将是一个字典数组;每个字典都有键“name”、“totalIncome”和“totalLoans”(具有相应的值)。