Hi I have following issue:
I’m programming a game and everytime the player finishes a score is submitted. So i got two Datasources: Score and Mode. And i want to sort these Highscores in 4 sections, the 4 modes i have. And in these sections it should be sorted by Score (highest on the top).
Yet I got this code:
- (NSFetchedResultsController *)fetchedResultsController{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"score" ascending:NO];
NSArray *sortDescriptors = @[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"mode" cacheName:nil];
_fetchedResultsController.delegate = self;
[_fetchedResultsController performFetch:nil];
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _fetchedResultsController;}
But all I get is a pretty random Sorting. The first time it worked but after a few games it messed up!
My modes are: 10,20,30,60 (seconds) The golden badge on the left shows what section it should be sorted in.
Hope someone can help me.
You need to add another sort descriptor for mode as well as for score.
You need to sort first by mode and then by score. As you are currently sorting by score and sectioning by name you’ll get…
Change your sort descriptor code like this…
That should sort it for you (pun very much intended 😉 )
If you would like four separate sections then your NSFRC will look like this…
This will then split the data into sections and rows.
Count of sections is
[[nsfrc allSections] count];And so on…