问题描述
我有一些这样的数据:
1,111,2,333,45,67,322,4445
1, 111, 2, 333, 45, 67, 322, 4445
NSArray *array = [[myData allKeys]sortedArrayUsingSelector: @selector(compare:)];
如果我运行此代码,它的排序方式如下:
If I run this code, it sorted like this:
但是我其实想要这个:
我该如何实现它? thz u。
How can I implement it? thz u.
推荐答案
扩展保罗林奇的答案,这里有一个例子我使用比较方法作为一个类别的NSString
。此代码仅处理数字后跟可选的非数字限定符的情况,但如果需要,您可以扩展它以处理1a10等情况。
Expanding on Paul Lynch's answer, here's an example I have doing exactly this using a comparison method as a category on NSString
. This code handles only the case of numbers followed by optional non-numeric qualifiers, but you could extend it to handle cases like "1a10" etc. if desired.
一旦你创建类别方法,你只需要做
Once you create the category method, you just need to do
[[myData的allKeys] sortedArrayUsingSelector:@selector(psuedoNumericCompare:)];
@interface NSString (Support)
- (NSComparisonResult) psuedoNumericCompare:(NSString *)otherString;
@end
@implementation NSString (Support)
// "psuedo-numeric" comparison
// -- if both strings begin with digits, numeric comparison on the digits
// -- if numbers equal (or non-numeric), caseInsensitiveCompare on the remainder
- (NSComparisonResult) psuedoNumericCompare:(NSString *)otherString {
NSString *left = self;
NSString *right = otherString;
NSInteger leftNumber, rightNumber;
NSScanner *leftScanner = [NSScanner scannerWithString:left];
NSScanner *rightScanner = [NSScanner scannerWithString:right];
// if both begin with numbers, numeric comparison takes precedence
if ([leftScanner scanInteger:&leftNumber] && [rightScanner scanInteger:&rightNumber]) {
if (leftNumber < rightNumber)
return NSOrderedAscending;
if (leftNumber > rightNumber)
return NSOrderedDescending;
// if numeric values tied, compare the rest
left = [left substringFromIndex:[leftScanner scanLocation]];
right = [right substringFromIndex:[rightScanner scanLocation]];
}
return [left caseInsensitiveCompare:right];
}
这篇关于如何让sortedArrayUsingSelector使用整数来排序而不是String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!