Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSSortDescriptor to keep 'nil' values at the bottom of a list

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;
like image 370
user3268266 Avatar asked Feb 14 '23 20:02

user3268266


2 Answers

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.

like image 86
Marcus S. Zarra Avatar answered Apr 09 '23 11:04

Marcus S. Zarra


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];
 }
like image 23
vokilam Avatar answered Apr 09 '23 12:04

vokilam