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.
source
share