从核心数据中获取子总和

Fetching child sum from Core Data

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

工资: 收入 税 相对:(对一个人)

账单 数量 相对:(对一个人)

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

李四,SUM>收入,SUM>金额 Eva Doe,SUM>收入,SUM>金额

使用Swift

这可能最容易使用键值编码 "collection operators"(参见 here)而不是获取来完成。对于每个 person:

let name = person.name
let totalIncome = person.valueForKeyPath("salary.@sum.income")
let totalLoans = person.valueForKeyPath("loans.@sum.amount")

如果性能是个问题,您可以通过将提取请求(针对 Person 对象)修改为 "prefetch" 相关的 SalaryBills 对象来改进:

fetchRequest.relationshipKeyPathsForPrefetching = ["salary", "loans"]

或者,可以一次获取所有所需信息,但我不推荐这样做,因为它需要将 fetchRequest 更改为 return 字典数组而不是 NSManagedObjects.这使得后续处理(例如填充您的 table 视图)更加困难。

// 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"(具有相应的值)。