I have an NSFetchRequest that is fetching an entity called "Player" and I want the results be sorted by 3 attributes in the following order:

Whether the attribute called "sendingoffOffence" is nil or not Whether the relationship in the entity at "team.homeMatch" is nil or not I want the strings in the "number" attribute to be sorted in ascending order.

Basically, I am looking to have all players that have a red card ("sendingOffOffence" is not nil) appear at the top of the list, then have the set be ordered by whether the player is on the home team or not, and then finally get the set of players on a team in an offense group be sorted by their jersey numbers.

As such, I use the following code in my fetch request:

// Set the entity for the fetch request NSEntityDescription *entity = [NSEntityDescription entityForName:@"Player" inManagedObjectContext:self.match.managedObjectContext]; [fetchRequest setEntity:entity]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"match == %@", self.match]; [fetchRequest setPredicate:predicate]; // Sort the results // Sort according to whether the user has a red card / sendingOffOffence NSSortDescriptor *hasRedCard = [[NSSortDescriptor alloc] initWithKey:@"sendingoffOffence" ascending:NO]; // Sort according to whether the user is on the home team or not NSSortDescriptor *isHomeTeam = [[NSSortDescriptor alloc] initWithKey:@"team.homeMatch" ascending:NO]; // Sort according to the player's jersey numbers NSSortDescriptor *number = [[NSSortDescriptor alloc] initWithKey:@"number" ascending:YES selector:@selector(localizedStandardCompare:)]; [fetchRequest setSortDescriptors:@[hasRedCard, isHomeTeam, number]]; // Set the amount of records to retrieve from the database [fetchRequest setFetchBatchSize:20]; NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.match.managedObjectContext sectionNameKeyPath:nil cacheName:@"MatchCache"]

However, when I execute the above code, I get the following results:

This sorting order is wrong because I want the following order to appear in the red card section:

11 - Home

12 - Home

0 - Away

11 - Away

21 - Away

And in the yellow card section:

1 - Home

2 - Home

99 - Home

1 - Away

31 - Away

It looks like the yellow card section sorts correctly but the red card section is showing very weird behavior that makes it appear that it is not getting sorted at all.

I am fairly stumped as to why the red card section fails to sort correctly - any thoughts? Should I just sort these objects in memory instead of relying on core data to get my preferred order?

Please be aware that this is a core data application with a SQL backed persistence store.

UPDATE

The following is the SQL statement that core data is using in my fetch: