GROUP BY equivalent for Core Data

后端 未结 4 692
离开以前
离开以前 2020-12-31 19:06

I know that I can use @distinctUnionOfObjects to find something like the following in SQL:

SELECT a_value
FROM my_table
GROUP BY a_value;

W

4条回答
  •  心在旅途
    2020-12-31 19:11

    I find this method (roughly similar to the accepted answer) to be a little cleaner and easier to understand. This is the SQL equivalent to:

    SELECT COUNT(*), a_value FROM my_table GROUP BY a_value;

    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:[MyTable className]];
    
    // create expression for grouped column
    NSExpressionDescription *aValueDescription = [[NSExpressionDescription alloc] init];
    aValueDescription.name = @"aValue"; // name of key in result dictionary
    aValueDescription.expression = [NSExpression expressionWithFormat:@"aValue"];
    aValueDescription.expressionResultType = NSObjectIDAttributeType;
    
    // create expression for count
    NSExpressionDescription *countDescription = [[NSExpressionDescription alloc] init];
    countDescription.name = @"count"; // name of dictionary key in result dictionary
    countDescription.expression = [NSExpression expressionWithFormat:@"aValue.@count"];
    countDescription.expressionResultType  = NSInteger32AttributeType;
    
    // fill out fetch request
    fetchRequest.propertiesToGroupBy = @[@"aValue"];
    fetchRequest.propertiesToFetch = @[aValueDescription, countDescription];
    //fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"count" ascending:NO]]; // not sure why this crashes
    fetchRequest.resultType = NSDictionaryResultType; // required for "group by" requests
    
    NSError *error = nil;
    NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    

    The returned results is an array of NSDictionary. Note that the description name properties can be anything you want - they are just the names of the keys in the returned dictionaries. One can add a predicate to the fetch request to filter rows from the table; this code returns all rows.

    Bonus points to anyone who can tell me how to make the sort descriptor work...

提交回复
热议问题