NSFetchedResultsController: sort descriptors and sections

霸气de小男生 提交于 2019-12-22 05:08:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/21280452/nsfetchedresultscontroller-sort-descriptors-and-sections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!