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

家住魔仙堡 提交于 2020-01-02 08:07:39

问题


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;

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/21643888/using-nssortdescriptor-to-keep-nil-values-at-the-bottom-of-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!