2
votes

I am trying to use the group-by core data functionality in its most basic form:

- (NSFetchedResultsController *)fetchedResultsController {

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];

    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    NSExpression *reviewNumKeyExpression = [NSExpression expressionForKeyPath:@"review_num"];
    NSExpression *reviewMaxExpression = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:reviewNumKeyExpression]];

    NSExpressionDescription *maxReviewED = [[NSExpressionDescription alloc] init];
    [maxReviewED setName:@"maxReview"];
    [maxReviewED setExpression:reviewMaxExpression];
    [maxReviewED setExpressionResultType:NSInteger32AttributeType];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Group" inManagedObjectContext:managedObjectContext];

    [fetchRequest setResultType:NSDictionaryResultType];
    [fetchRequest setReturnsDistinctResults:YES];
    [fetchRequest setEntity:entity];

    NSAttributeDescription *groupId = [entity.propertiesByName objectForKey:@"group_id"];
    NSArray *propertiesToFetch = [NSArray arrayWithObjects:groupId, maxReviewED, nil];
    [fetchRequest setPropertiesToFetch:propertiesToFetch];
    [fetchRequest setPropertiesToGroupBy:propertiesToFetch];
...

When running this code, I get the following error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid keypath expression ((), name maxReview, isOptional 1, isTransient 0, entity (null), renamingIdentifier maxDepartment, validation predicates ( ), warnings ( ), versionHashModifier (null) userInfo { }) passed to setPropertiesToFetch

I guess I am missing something with the API, so any help would be very much appreciated!

1

1 Answers

2
votes

I think the error message is wrong: the problem is in the setPropertiesToGroupBy, not the setPropertiesToFetch. You cannot group by a computed value (maxReview), but I doubt you actually want to: if you want the maximum value of review_num for each groupId, you only need groupId in the propertiesToGroupBy:

NSAttributeDescription *groupId = [entity.propertiesByName objectForKey:@"group_id"];
NSArray *propertiesToFetch = [NSArray arrayWithObjects:groupId, maxReviewED, nil];
NSArray *propertiesToGroupBy = [NSArray arrayWithObjects:groupId, nil];
[fetchRequest setPropertiesToFetch:propertiesToFetch];
[fetchRequest setPropertiesToGroupBy:propertiesToGroupBy];