Core Data Sort By Multiple Sort Descriptors With CaseInsensitiveCompare
Asked Answered
G

1

10

I have a Word : NSManagedObject subclass that I'm trying to group by the first letter of the word. In each section I'm then trying to sort by the length property while maintain the alphanumeric sort when words have the same length. So it would appear like

A Words

  • apple Length = 5
  • axe Length = 3
  • am Length = 2

B Words

  • bane Length = 4
  • boat Length = 4
  • bag Length = 3

So I init a new NSFetchRequest first. Then I add my sort descriptors, first sorting by the value (which is just the word), then sorting by the length. Finally init my fetchedResultsController and using the group value to group them by the first letter. Here is my code but I'm not getting the desired result. Any help would be greatly appreciated.

@interface Word : NSManagedObject

@property (nonatomic, retain) NSString * value;
@property (nonatomic, retain) NSString * group;
@property (nonatomic, retain) NSNumber * length;

@end

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Word"];
request.sortDescriptors = [NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"value" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)],
                               [NSSortDescriptor sortDescriptorWithKey:@"length" ascending:NO], nil];

self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                        managedObjectContext:self.wordDatabase.managedObjectContext
                                                                          sectionNameKeyPath:@"group"
                                                                                   cacheName:nil];
Guanaco answered 29/1, 2013 at 3:27 Comment(0)
R
23

The first sort descriptor should be for the key used as sectionNameKeyPath, the second sort descriptor for the key length and the last one for value:

request.sortDescriptors = [NSArray arrayWithObjects:
    [NSSortDescriptor sortDescriptorWithKey:@"group" ascending:YES],
    [NSSortDescriptor sortDescriptorWithKey:@"length" ascending:NO],
    [NSSortDescriptor sortDescriptorWithKey:@"value" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)],
    nil];
Rhombohedron answered 29/1, 2013 at 6:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.