Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data Sort By Multiple Sort Descriptors With CaseInsensitiveCompare

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];
like image 297
aahrens Avatar asked Jan 29 '13 03:01

aahrens


1 Answers

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];
like image 52
Martin R Avatar answered Oct 20 '22 20:10

Martin R