Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data sum in relationship

I have a Category entity which has many expenses. I want to get the sum of all expenses for a category in a given 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:@"[email protected]"];

}

The problem with this code is that it throws an exception because apparently that's not the way to use @sum on a relationship.

like image 453
Oscar Del Ben Avatar asked Nov 06 '22 02:11

Oscar Del Ben


2 Answers

Your using the @sum with the correct syntax. Most likely, you have just got another part of the keypath wrong e.g. "expenses" instead of "expense". Alternatively, you may be fetching the wrong entity.

If all you want to do is fetch this sum, do an attribute fetch and set your return type to dictionary. (See NSFetchRequest and Core Data Programming Guide) docs for details. That returns an array of dictionaries whose sole key is the attribute name and whose sole value is the value of selected attribute of one managed object. It's faster and uses fewer resources than fetching full objects.

like image 177
TechZen Avatar answered Nov 12 '22 10:11

TechZen


You might need to create a custom getter for it, and access it from there.

i.e.

Category.h

@property (nonatomic, readonly) NSNumber* expensesSum;    

Category.m

-(NSNumber*) expensesSum
{
    return [self valueForKeyPath:@"[email protected]"];
}

Also, you're currently returning NSNumber * when the request returns an array of children objects I believe.

like image 27
Dominic Tancredi Avatar answered Nov 12 '22 10:11

Dominic Tancredi