这可能最容易使用键值编码“集合运算符”来完成(请参阅here https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html#//apple_ref/doc/uid/20002176-BAJEAIEE)而不是获取。对于每个person
:
let name = person.name
let totalIncome = person.valueForKeyPath("[email protected] /cdn-cgi/l/email-protection")
let totalLoans = person.valueForKeyPath("[email protected] /cdn-cgi/l/email-protection")
如果性能是一个问题,您可以通过修改获取请求(针对 Person 对象)来“预取”相关的内容来改进问题Salary
and Bills
对象:
fetchRequest.relationshipKeyPathsForPrefetching = ["salary", "loans"]
或者,可以在一次 fetch 中检索所有所需信息,但我不推荐这样做,因为它需要更改 fetchRequest 以返回一组字典而不是一组NSManagedObjects
。这使得后续处理(例如填充表视图)变得更加困难。
// Define NSExpression and NSExpressionDescription for the total income
let incomeED = NSExpressionDescription()
incomeED.expression = NSExpression(forKeyPath: "[email protected] /cdn-cgi/l/email-protection")
incomeED.name = "totalIncome"
incomeED.expressionResultType = .Integer64AttributeType
// Define NSExpression and NSExpressionDescription for the total amount
let amtED = NSExpressionDescription()
amtED.expression = NSExpression(forKeyPath: "[email protected] /cdn-cgi/l/email-protection")
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”(具有相应的值)。