用数字排序字符串的NSArray

时间:2015-03-21 07:47:23

标签: ios objective-c nsarray

我有一个包含这些字符串的数组。

@"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",

1 个答案:

答案 0 :(得分:2)

此代码示例将起到魔力。

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);