使用NSSortDescriptor将空白字符串放在排序末尾的简单方法? [英] Easy way to put blank strings at end of sort using NSSortDescriptor?
问题描述
我正在使用NSSortDescriptor
对NSDictionary
个项目的NSArray
进行排序.效果很好,正是我所需要的...除了我希望字典项的排序键具有空白值的项显示在排序列表的末尾.有没有一种方法可以轻松实现这一目标?还是我必须创建一些自定义排序功能?不,我不想只是将其设置为DESC顺序...我希望排序的结果看起来像是A,A,B,B,C,空白,空白.
I'm using NSSortDescriptor
to sort an NSArray
of NSDictionary
items. Works great, just what I needed... except that I'd like for the dictionary items that have blank values for my sort key to show up at the end of the sorted list. Is there a way to easily accomplish this? Or will I have to create some custom sorting functions? And no, I don't want to just set it to DESC order... I'd like sorted results to look like A, A, B, B, C, blanks, blank.
推荐答案
在看到另一个使用自定义比较的示例后,想到了这一点.这是我最后得到的代码:
Figured this out after seeing another example using a custom comparison. Here is the code I ended up with:
@interface NSString (CustomStatusCompare)
- (NSComparisonResult)customStatusCompare:(NSString*)other;
@end
@implementation NSString (CustomStatusCompare)
- (NSComparisonResult)customStatusCompare:(NSString*)other {
NSAssert([other isKindOfClass:[NSString class]], @"Must be a NSString");
if ([self isEqual:other]) {
return NSOrderedSame;
}
else if ([self length] > 0 && [other length] > 0) {
return [self localizedCaseInsensitiveCompare:other];
}
else if ([self length] > 0 && [other length] == 0) {
return NSOrderedAscending;
}
else {
return NSOrderedDescending;
}
}
@end
NSSortDescriptor *serviceTypeDescriptor =
[[NSSortDescriptor alloc] initWithKey:@"Service"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)];
NSSortDescriptor *locationDescriptor =
[[NSSortDescriptor alloc] initWithKey:@"Location"
ascending:YES
selector:@selector(customStatusCompare:)]; //using custom comparison here!
NSArray *descriptors = [NSArray arrayWithObjects:locationDescriptor, nameDescriptor, nil];
self.navArray = [self.navArray sortedArrayUsingDescriptors:descriptors];
因此,如果两个字符串都不为空,则比较器返回NSOrderedSame ...如果两个字符串均为非空,则调用常规比较函数...如果只有一个字符串为空,则它将反转该比较的常规顺序.瞧!
So the comparer returns NSOrderedSame if both strings are empty... calls the regular comparison function if both strings are non-empty... if only one string is empty, it reverses the normal order of that comparison. Voila!
这篇关于使用NSSortDescriptor将空白字符串放在排序末尾的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!