0

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?

Gabriel.Massana
  • 8,165
  • 6
  • 62
  • 81

2 Answers2

1

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.

Jody Hagins
  • 27,943
  • 6
  • 58
  • 87
0

I think the previous answer is not quite right. In your fetched results controller, you do the usual things but

  • You fetch the entity Color
  • You sort by name (that would be the name of the color)

In cellForRowAtIndexPath: you construct the appropriate string to display.

Color *color = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:@"%@ (%d)", 
   color.name, color.cars.count];

where cars is the name of the inverse relationship from color to the cars.

Mundi
  • 79,884
  • 17
  • 117
  • 140