Skip to content

Instantly share code, notes, and snippets.

@paykroyd
Created September 7, 2012 21:16
Show Gist options
  • Save paykroyd/3669723 to your computer and use it in GitHub Desktop.
Save paykroyd/3669723 to your computer and use it in GitHub Desktop.
Group By in Core Data
NSFetchRequest *request = [self fetchRequestForType:CORE_DATA_BLOCK_TYPE];
NSEntityDescription* entity = [NSEntityDescription entityForName:CORE_DATA_BLOCK_TYPE
inManagedObjectContext:self.managedObjectContext];
NSAttributeDescription* typeDesc = [entity.attributesByName objectForKey:@"type"];
NSExpression *countExpression = [NSExpression expressionForFunction: @"count:"
arguments: [NSArray arrayWithObject:[NSExpression expressionForKeyPath: @"type"]]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName: @"count"];
[expressionDescription setExpression: countExpression];
[expressionDescription setExpressionResultType: NSInteger32AttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObjects:typeDesc, expressionDescription, nil]];
[request setPropertiesToGroupBy:[NSArray arrayWithObject:typeDesc]];
[request setResultType:NSDictionaryResultType];
if (notebook)
[request setPredicate:[NSPredicate predicateWithFormat:@"%@ in notebooks AND isSearchable == TRUE AND transient == FALSE", notebook.block]];
else
[request setPredicate:[NSPredicate predicateWithFormat:@"isSearchable == TRUE AND transient == FALSE"]];
NSError* error = nil;
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];
@subramanya2107
Copy link

Hello ,is there a way to group by expressionDescription

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment