swift - 从核心数据中获取子总和

标签 swift core-data nspredicate executefetchrequest

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

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

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

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

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 对象)以“预获取”相关的 SalaryBills 对象来改进:

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/

相关文章:

ios - IQKeyboard 未在堆栈 View 中显示下一个/上一个选项

ios - 使用对象过滤 NSSet 以获取具有最大属性值的对象

swift - xctest 使用 NSPredicate 最终取代 Quick/Nimble

ios - 如何从核心数据(实体)中删除行 ios swift

ios - 如何使用 NSSet 正确编码核心数据下钻

ios - 核心数据 : Query to one-to-many-to-many relationship

ios - 使用批处理在 Firestore 内增加值 - "Ambiguous use of ' 增量'"

ios - SpriteKit 矢量图形性能

ios - 创建一个椰子

ios - 为什么 nspredicate 不起作用