3

3 つのエンティティがあるとします。 Person: 氏名住所 (to-many-salary) および (to-many-loans)

給与: 所得税 Rel: (対1人)

請求 額 Rel: (1人あたり)

次のような結果になるフェッチを実行するにはどうすればよいですか。

John Doe, SUM>収入, SUM>額 Eva Doe, SUM>収入, SUM>額

スウィフトの使用

4

1 に答える 1

5

これはおそらく、フェッチではなくKey Value Coding の「コレクション演算子」(こちらを参照) を使用して最も簡単に実行できます。ごとにperson:

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

Salaryパフォーマンスが問題になる場合は、(Person オブジェクトの) フェッチ要求を修正して、関連するオブジェクトとオブジェクトを「プリフェッチ」することで、状況を改善できBillsます。

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

または、必要な情報をすべて 1 回のフェッチで取得することもできますが、お勧めしません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

フェッチの結果は辞書の配列になります。各ディクショナリには、「name」、「totalIncome」、「totalLoans」(対応する値) というキーがあります。

于 2016-01-01T14:34:34.567 に答える