The main amount of data in the ratio

I have a category object that has a lot of costs. I want to get the sum of all expenses for a category for this month:

- (NSNumber *)totalForMonth:(NSDate *)date { ...

NSPredicate *sumPredicate = [NSPredicate predicateWithFormat:@"(ANY %@ <= expenses.created_at) AND (ANY expenses.created_at <= %@)",
                             [date beginningOfMonth], [date endOfMonth]];

NSFetchRequest *req = [[[NSFetchRequest alloc] init] autorelease];
[req setPredicate:sumPredicate];
[req setEntity:entity];

NSError *error;
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:req error:&error];

return [fetchedObjects valueForKeyPath:@"expenses.@sum.amount"];

}

code>

The problem with this code is that it throws an exception, because apparently this is not a way to use @sum for a relationship.

+5
source share
2 answers

Using @sum with the correct syntax. Most likely, you just had the wrong error. "expenses" instead of "expenses". In addition, you may receive the wrong object.

, , , . (. NSFetchRequest Core Data). , . , .

+1

getter .

.

Category.h

@property (nonatomic, readonly) NSNumber* expensesSum;    

Category.m

-(NSNumber*) expensesSum
{
    return [self valueForKeyPath:@"expenses.@sum.amount"];
}

, NSNumber *, , .

+1

All Articles