簡単な解決策は、適切に計算された金額を与えるExpenseクラスの別のメソッドを実装することです。
など。
- (NSDecimalNumber *) calculatedExpenseAmount {
NSDecimalNumber *actualAmount = self.expenseAmount;
// Pseudo-code begins
if (self.expenseCategory != nil) {
actualAmount = self.expenseAmount * self.expenseCategory.unitRate;
}
return actualAmount;
}
私は私の前の回答にに追加しています。
すべての管理オブジェクトを取得しないようにするには、NSDictionary-resultクエリを使用して、expenseAmountおよびexpenseCategory.unitRate値を引き出すことができます。
- (NSDecimalNumber *) totalExpenses
{
// Fetch all of the expense amounts and unit rate of any related category.
NSFetchRequest *request = ...;
[request setManagedObjectContext:<...>];
[request setEntity:<ExpenseAccountDescription>];
[request setResultType:NSDictionaryResultType];
NSArray *props = [NSArray arrayWithObjects:@"expenseAmount", @"category.unitRate", nil];
[request setPropertiesToFetch:props];
NSArray *amounts = [request executeRequest:...];
// amounts is an array of dictionaries, each hold the desired property values.
// Loop and sum the individual amounts
NSDecimal *total = [[NSDecimalNumber zero] decimalNumber];
NSAutoreleasePool *pool = nil; // contain the mess
NSCalculationError err = NSCalculationNoError;
for (NSDictionary *result in amounts)
{
pool = [NSAutoreleasePool new];
NSDecimal newTotal = [[NSDecimalNumber zero] decimalNumber];
NSDecimalNumber *expenseAmount = [result valueForKeyPath:@"expenseAmount"];
NSDecimalNumber *unitRate = [result valueForKeyPath:@"category.unitRate"];
if (unitRate != nil) {
// do the unit rate multiplication and accumulate the result in the total
NSDecimal calculated = [[NSDecimalNumber zero] decimalNumber];
err = NSDecimalMultiply (&calculated, [expenseAmount decimalNumber], [unitRate decimalNumber], NSRoundBankers);
if (err == NSCalculationNoError) {
err = NSDecimalAdd (&newTotal, total, calculated, NSRoundBankers);
}
}
else {
// just accumulate the result in the total
err = NSDecimalAdd (&newTotal, total, [expenseAmount decimalNumber], NSRoundBankers);
}
// Keep the new total
NSDecimalCopy(&total, newTotal);
[pool drain];
}
return [NSDecimalNumber decimalNumberWithDecimal:total];
}
費用エントリが10000件ある場合、このフェッチと計算には1MB未満のRAMが必要です。インストゥルメントはそれを測定する際にあなたの友人となります
ありがとうございます。私も同様の問題があり、NSExpressionは私のためには機能しませんでした - 私は倍精度とタイムスタンプで作業しています。何らかの理由でdivide:by:関数が奇妙な結果を生成します。あなたの最終的な解決策については私の計算に複数のレコードを含める必要があるので、私は興味があります。 –