OGeek|极客世界-中国程序员成长平台

标题: ios - 使用 NSSortDescriptor 将空白字符串放在排序末尾的简单方法? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:18
标题: ios - 使用 NSSortDescriptor 将空白字符串放在排序末尾的简单方法?

我正在使用 NSSortDescriptorNSDictionary 项目的 NSArray 进行排序。效果很好,正是我需要的...除了我希望排序键具有空​​白值的字典项显示在排序列表的末尾。有没有办法轻松实现这一点?还是我必须创建一些自定义排序功能?不,我不想只是将其设置为 DESC 顺序...我希望排序结果看起来像 A、A、B、B、C、空白、空白。



Best Answer-推荐答案


在看到另一个使用自定义比较的示例后发现了这一点。这是我最终得到的代码:

@interface NSString (CustomStatusCompare)
- (NSComparisonResult)customStatusCompareNSString*)other;
@end

@implementation NSString (CustomStatusCompare)
- (NSComparisonResult)customStatusCompareNSString*)other {
    NSAssert([other isKindOfClass:[NSString class]], @"Must be a NSString");
    if ([self isEqualther]) {
        return NSOrderedSame;
    }
    else if ([self length] > 0 && [other length] > 0) {
        return [self localizedCaseInsensitiveComparether];        
    }
    else if ([self length] > 0 && [other length] == 0) {
        return NSOrderedAscending;
    }
    else {
        return NSOrderedDescending;
    } 
}
@end



NSSortDescriptor *serviceTypeDescriptor =
[[NSSortDescriptor alloc] initWithKey"Service"
                             ascending:YES
                             selectorselector(localizedCaseInsensitiveCompare];

NSSortDescriptor *locationDescriptor = 
[[NSSortDescriptor alloc] initWithKey"Location"
                             ascending:YES
                             selectorselector(customStatusCompare];  //using custom comparison here!

NSArray *descriptors = [NSArray arrayWithObjects:locationDescriptor, nameDescriptor, nil];        
self.navArray = [self.navArray sortedArrayUsingDescriptors:descriptors];

因此,如果两个字符串都为空,则比较器返回 NSOrderedSame...如果两个字符串都不为空,则调用常规比较函数...如果只有一个字符串为空,它会反转该比较的正常顺序。瞧!

关于ios - 使用 NSSortDescriptor 将空白字符串放在排序末尾的简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9743890/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4