我已经看到很多问题如何排序1,10,2,3等。
我在表单中导入了一些Json数据:@"arrived"
,@"boarding"
,@"1"
,@"2"
,@"3"
等。
我目前只有一个不区分大小写的排序:
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"time" ascending:YES selector:@selector(caseInsensitiveCompare:)];
首先对这些数字进行排序,然后按照上面显示的形式对单词进行排序。
我有什么选择呢?感谢
答案 0 :(得分:3)
这个冗长的比较器可以解决这个问题:
NSArray *testArray = @[@"3", @"boarding", @"2", @"arrived", @"1"];
NSArray *sortedArray = [testArray sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
NSInteger firstInteger = 0;
BOOL isInteger1 = [[NSScanner scannerWithString:obj1] scanInteger:&firstInteger];
NSInteger secondInteger = 0;
BOOL isInteger2 = [[NSScanner scannerWithString:obj2] scanInteger:&secondInteger];
if (isInteger1 && isInteger2) {
// Normal integer comparison
if (firstInteger > secondInteger) {
return NSOrderedDescending;
}
else if (secondInteger > firstInteger) {
return NSOrderedAscending;
}
else {
return NSOrderedSame;
}
}
else if (isInteger1) {
return NSOrderedDescending;
}
else if (isInteger2) {
return NSOrderedAscending;
}
else {
return [obj1 compare:obj2 options:NSCaseInsensitiveSearch];
}
}];
修改强>
示例输出:
Printing description of sortedArray:
<__NSArrayI 0x7ffacaa26da0>(
arrived,
boarding,
1,
2,
3
答案 1 :(得分:2)
尝试这个
NSComparator compare=^(id obj1, id obj2) {
NSString *s1 = [obj1 substringToIndex:1];
NSString *s2 = [obj2 substringToIndex:1];
NSRange r1 = [s1 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
NSRange r2 = [s2 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
if (r1.location == r2.location ) { // either both start with a number or both with a letter
return [obj1 compare:obj2 options:NSDiacriticInsensitiveSearch|NSCaseInsensitiveSearch];
} else { // one starts wit a letter, the other with a number
if ([s1 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location == NSNotFound) {
return NSOrderedAscending;
}
return NSOrderedDescending;
}
};
NSSortDescriptor *desc=[[NSSortDescriptor alloc]initWithKey:@"time" ascending:YES comparator:compare];
originalArray = [originalArray sortedArrayUsingDescriptors:@[desc]];
可以帮到你。