Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFetchedResultsController: sort descriptors and sections

I have a core data model like so...

[Country] <--->> [League] <--->> [Match]

And I'm using an NSFetchedResultsController to display the Matches into a UITableView.

I've done this a million times before but for some reason the sections are going wrong and I can't work out why.

I have created the sort descriptors like so...

NSSortDescriptor *countrySD = [NSSortDescriptor sortDescriptorWithKey:@"league.country.name" ascending:YES];
    NSSortDescriptor *leagueSD = [NSSortDescriptor sortDescriptorWithKey:@"league.name" ascending:YES];
    NSSortDescriptor *dateSD = [NSSortDescriptor sortDescriptorWithKey:@"startDate" ascending:YES];
    request.sortDescriptors = @[countrySD, leagueSD, dateSD];

First I want to check I have put these in the correct order. This should first sort by the country.name then sort by the league.name and then sort by the startDate.

i.e.

  1. Anything in Albania should come before anything in Spain.
  2. In a single country, anything in League 1 should come before anything in League 2.
  3. In a single league all the matches should be displayed in startDate order with the earliest first.

Then I'm creating the NSFRC with this...

_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.moc sectionNameKeyPath:@"league.leagueID" cacheName:nil];

So this should group the table by matches with different league.leagueID values.

It should be something like...

Albania - League 1
    12:00
    13:00
Albania - League 2
    09:00
    14:00
France - League 1
    09:00
Spain - A League
    08:00
    12:00
Spain - B League
    09:00

It isn't working though. I get multiple headers for the same league. Some of the matches appear under the wrong header etc...

I've checked the values (NSLogged) of the matches appearing under the wrong league and they actually have the correct league. So even though they have Spain - A League they are appearing under France - League A (for example).

Any idea how I can fix this?

like image 636
Fogmeister Avatar asked Jan 22 '14 10:01

Fogmeister


1 Answers

The key path used as sectionNameKeyPath argument must be the same key used in the first sort descriptor (or generate the same relative ordering).

There is (as far as I know) no way to use two or more sort descriptors for grouping the results of a fetched results controller into sections.

like image 142
Martin R Avatar answered Sep 28 '22 12:09

Martin R