Question

I'm working on sorting NSFetchedResultController data. I need to sort data by their first name. However, there are some entries with no first name.

I need the "no first name" objects to appear the bottom of the list, rather than the top. With the current code, when I sort the list by first name, the "no first name" cells are placed at the top.

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Contacts"];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES]];
_FRC = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                            managedObjectContext:MOC
                                           sectionNameKeyPath:nil cacheName:nil];   
_FRC.delegate = self;
Was it helpful?

Solution

Update after some consulting with colleagues :)

First, are you talking about "blank" as in a string with spaces in it or 'nil' which is a property with no value at all?

An idea that came up would be to add a BOOL called hasFirstName and then sort first on the hasFirstName and then sort on firstName.

OTHER TIPS

NSSortDescriptor has sortDescriptorWithKey:ascending:comparator: method. Using this method you can make custom comparison and move empty items to the bottom. Comparator block may look like this:

^NSComparisonResult(NSString *obj1, NSString *obj2) {
     if (obj1.length == 0) {
         return NSOrderedDescending;
     }
     if (obj2.length == 0) {
         return NSOrderedAscending;
     }

     return [obj1 compare:obj2];
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top