एक आसान समाधान आपके व्यय वर्ग पर एक और विधि लागू करने के लिए हो सकता है जो आपको उचित गणना की गई राशि देता है।
उदा।
- (NSDecimalNumber *) calculatedExpenseAmount {
NSDecimalNumber *actualAmount = self.expenseAmount;
// Pseudo-code begins
if (self.expenseCategory != nil) {
actualAmount = self.expenseAmount * self.expenseCategory.unitRate;
}
return actualAmount;
}
मैं अपने पिछले जवाब देने के लिए पर जोड़ रहा।
यदि आप प्रत्येक प्रबंधित ऑब्जेक्ट में खींचने से बचना चाहते हैं, तो आप खर्च को निकालने के लिए NSDictionary-result क्वेरी का उपयोग कर सकते हैं .उंट और व्यय Category.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 व्यय प्रविष्टियां हैं, तो इस fetch और गणना में 1 एमबी से कम रैम लग सकता है। उपकरण मापने में आपका मित्र होगा।
स्रोत
2011-01-20 08:32:56
इस प्रश्न के लिए धन्यवाद। मुझे एक ही समस्या है और एनएसईएक्सप्रेस ने मेरे लिए काम नहीं किया - मैं युगल और टाइमस्टैम्प के साथ काम कर रहा हूं और किसी कारण से विभाजन: द्वारा: फ़ंक्शन अजीब परिणाम उत्पन्न करता है। मैं आपके अंतिम समाधान के बारे में उत्सुक हूं क्योंकि मुझे अपनी गणना में एक से अधिक रिकॉर्ड शामिल करने की भी आवश्यकता है। –