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];

1 Answer 1

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];
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.