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

点点圈 提交于 2019-12-06 03:34:49

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.

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