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:@"expenses.@sum.amount"];
}
The problem with this code is that it throws an exception because apparently that's not the way to use @sum on a relationship.
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.
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:@"expenses.@sum.amount"];
}
Also, you're currently returning NSNumber *
when the request returns an array of children objects I believe.
精彩评论