Search code examples
ioscore-dataios5countnsfetchrequest

Core Data attribute count and show the result in a TableView


I've got an entity called Car with 2 attributes: name and color.

I have several cars in the database:

name: Honda Civic

color: Blue

name: VW Golf

color: Blue

name: Renault Twingo

color: Red

name: Chevrolet Camaro

color: White

Now I need to count how many cars are there of each color and then put the results in a UITableView.

So, for example, in the TableView would have:

Blue (2)

Red (1)

White (1)

Imagine that there are about 70 different colors.

I searched many websites and books of Core Data, but still I do not know if this is possible.

Is it possible? If possible, how to do it?


Solution

  • These are simple fetches. In fact, you can use a NSFetchedResultsController, and set "color" as the section name, and it will return to you an array of all objects, and they will be grouped by color.

    Something like...

    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Car"];    
    NSSortDescriptor *sectionSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"color" ascending:YES];
    NSSortDescriptor *nameSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:sectionSortDescriptor, nameSortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];
    
    NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"color" cacheName:@"CarCache"];
    fetchedResultsController.delegate = self;
    self.fetchedResultsController = fetchedResultsController;
    
    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error]) {
        // Handle error...
    }
    

    Now, your data will be broken up into sections, one section per color, and the values in there sorted by name. To get the data, just look at the sections property of the FRC.