用数字对字符串的 NSArray 进行排序
sorting NSArray of strings with numbers
我有一个包含这些字符串的数组。
@"Common Area",
@"Building 1",
@"Building 2",
@"Building 3",
@"Building 4",
@"Building 10",
@"Building 14",
@"Car Park",
然后我尝试像这样按字母顺序排序
areaArray = [areaArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
但是它显示的像
@"Building 1",
@"Building 10",
@"Building 14",
@"Building 2",
@"Building 3",
@"Building 4",
@"Car Park",
@"Common Area",
我希望它显示为
@"Building 1",
@"Building 2",
@"Building 3",
@"Building 4",
@"Building 10",
@"Building 14",
@"Car Park",
@"Common Area",
此代码示例将发挥神奇作用。
NSArray *stringsArray = @[@"Common Area", @"Building 1", @"Building 2", @"Building 3", @"Building 4", @"Building 10", @"Building 14", @"Car Park"];
static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch |
NSNumericSearch |
NSWidthInsensitiveSearch | NSForcedOrderingSearch;
NSLocale *currentLocale = [NSLocale currentLocale];
NSComparator finderSortBlock = ^(id string1, id string2) {
NSRange string1Range = NSMakeRange(0, [string1 length]);
return [string1 compare:string2 options:comparisonOptions range:string1Range
locale:currentLocale];
};
NSArray *finderSortArray = [stringsArray sortedArrayUsingComparator:finderSortBlock];
NSLog(@"finderSortArray: %@", finderSortArray);
我有一个包含这些字符串的数组。
@"Common Area",
@"Building 1",
@"Building 2",
@"Building 3",
@"Building 4",
@"Building 10",
@"Building 14",
@"Car Park",
然后我尝试像这样按字母顺序排序
areaArray = [areaArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
但是它显示的像
@"Building 1",
@"Building 10",
@"Building 14",
@"Building 2",
@"Building 3",
@"Building 4",
@"Car Park",
@"Common Area",
我希望它显示为
@"Building 1",
@"Building 2",
@"Building 3",
@"Building 4",
@"Building 10",
@"Building 14",
@"Car Park",
@"Common Area",
此代码示例将发挥神奇作用。
NSArray *stringsArray = @[@"Common Area", @"Building 1", @"Building 2", @"Building 3", @"Building 4", @"Building 10", @"Building 14", @"Car Park"];
static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch |
NSNumericSearch |
NSWidthInsensitiveSearch | NSForcedOrderingSearch;
NSLocale *currentLocale = [NSLocale currentLocale];
NSComparator finderSortBlock = ^(id string1, id string2) {
NSRange string1Range = NSMakeRange(0, [string1 length]);
return [string1 compare:string2 options:comparisonOptions range:string1Range
locale:currentLocale];
};
NSArray *finderSortArray = [stringsArray sortedArrayUsingComparator:finderSortBlock];
NSLog(@"finderSortArray: %@", finderSortArray);