Using NSFetchedResultsController to return objects with ordered relationships

I have the following Core Data structure:

Event <<-->> Team <<-->> Player 

(all relationships are many-to-many and Event>Team & Team>Player are ordered relationships).

Pseudo code...

self.event = an instance of Event that has been populated earlier on in the process.
linkedTeams = the relationship between Team & Player.

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *thisEntry = [NSEntityDescription entityForName:@"Player" inManagedObjectContext:self.doc.managedObjectContext];
[fetchRequest setEntity:thisEntry];

NSPredicate *fetchPredicate = [NSPredicate predicateWithFormat:@"ANY %@ IN linkedTeams", self.events.teams];
[fetchRequest setPredicate:predicate];


NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.doc.managedObjectContext sectionNameKeyPath:nil cacheName:nil];

This will pull out all the Players in self.event.teams fine, the predicate works, but, I want to have the Players sorted by Team and Player (by using the ordered relationship), and split into sections (using Team as the section header).

How do I order the Players as per the Ordered relationship if pulling directly from the Players entities, it seems like this just isn't possible with NSSortDescriptor?

I can't have "sectionNameKeyPath = linkedTeams.name" because linkedTeams is a to-many relationship (even though it will only ever return 1 team in this scenario). Is there any way of doing this with the NSFetchedResultsController or am I best just creating my own data source form my property self.event?

Thanks for any help!


The problem is that a player can occur two or more times in your table view (because a player can be on more than one team). It is difficult to use a fetched results controller to fetch entities more than once.

Instead you could fetch the teams. Adjust your datasource methods to reference the team name as the section title, and populate the rows with the ordered relationship to players. Now, if a player is in more than one team, it will simply be displayed again.

If you do not want one player to be on more than two teams, you will need to change your data model to

Event <<-->> Team <--->> Player 

Your task should then be trivial.

NB: Besides, the ordered relationship has in my experience turned out to be of limited use and flexibility being quite cumbersome and error-prone in many situations. In all cases I have introduced a sequence attribute to keep track of the order myself.

链接地址: http://www.djcxy.com/p/36158.html

上一篇: NSFetchedResultsController的顺序应该不会改变

下一篇: 使用NSFetchedResultsController返回具有有序关系的对象