从核心数据中获取子总和 [英] Fetching child sum from Core Data
问题描述
让我们说我有三个实体.人员:名称地址(多工资)和(多贷款)
Lets say I have three Entitys. Person: name address (to-many-salary) and (to-many-loans)
工资:收入税相对:(一个人)
Salary: income tax Rel: (to-one-Person)
账单数量相对:(一对一)
Bills amount Rel: (to-one-person)
如何执行具有以下结果的提取:
How do I perform a fetch that have a result like this:
John Doe,SUM>收入,SUM>金额Eva Doe,SUM>收入,SUM>金额
John Doe, SUM>income, SUM>amount Eva Doe, SUM>income, SUM>amount
使用Swift
推荐答案
This is probably most easily done using Key Value Coding "collection operators" (see here) rather than a fetch. For each person
:
let name = person.name
let totalIncome = person.valueForKeyPath("salary.@sum.income")
let totalLoans = person.valueForKeyPath("loans.@sum.amount")
如果性能是一个问题,则可以通过修改获取请求(针对Person对象)来预取"相关的 Salary
和 Bills
对象:/p>
If performance is an issue, you might improve things by amending the fetch request (for the Person objects) to "prefetch" the related Salary
and Bills
objects:
fetchRequest.relationshipKeyPathsForPrefetching = ["salary", "loans"]
或者,可以一次取回所有必需的信息,尽管我不建议这样做,因为它需要更改fetchRequest以返回字典数组而不是 NSManagedObjects
数组.这使得后续处理(例如,填充表格视图)更加困难.
Alternatively, it is possible to retrieve the required information all in one fetch, though I do not recommend it because it requires changing the fetchRequest to return an array of dictionaries rather than an array of NSManagedObjects
. This makes subsequent processing (eg. populating your table view) more difficult.
// 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
提取的结果将是一个字典数组;每个字典将具有键名称","totalIncome"和"totalLoans"(具有相应的值).
The result of the fetch will be an array of dictionaries; each dictionary will have keys "name", "totalIncome" and "totalLoans" (with corresponding values).
这篇关于从核心数据中获取子总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!