GROUP BY equivalent for Core Data

后端 未结 4 664
离开以前
离开以前 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:23

    It's analog

    SELECT 'Status', COUNT(*) FROM 'Records' GROUP BY 'Status':

    NSFetchRequest* fetch = [NSFetchRequest fetchRequestWithEntityName:@"Record"];
    NSEntityDescription* entity = [NSEntityDescription entityForName:@"Record"
                                              inManagedObjectContext:myManagedObjectContext];
    NSAttributeDescription* statusDesc = [entity.attributesByName objectForKey:@"status"];
    NSExpression *keyPathExpression = [NSExpression expressionForKeyPath: @"url"]; // Does not really matter
    NSExpression *countExpression = [NSExpression expressionForFunction: @"count:"
                                                              arguments: [NSArray arrayWithObject:keyPathExpression]];
    NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
    [expressionDescription setName: @"count"];
    [expressionDescription setExpression: countExpression];
    [expressionDescription setExpressionResultType: NSInteger32AttributeType];
    [fetch setPropertiesToFetch:[NSArray arrayWithObjects:statusDesc, expressionDescription, nil]];
    [fetch setPropertiesToGroupBy:[NSArray arrayWithObject:statusDesc]];
    [fetch setResultType:NSDictionaryResultType];
    NSError* error = nil;
    NSArray *results = [myManagedObjectContext executeFetchRequest:fetch
                                                             error:&error];
    

    Found here

提交回复
热议问题