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;
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
.
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With