3

所以我有以下代码:

NSArray *pathArray = @[@"path/Documents/page9.png",
    @"path/Documents/page8.png",
    @"path/Documents/page10.png",
    @"path/Documents/page11.png",
    @"path/Documents/page0.png",
    @"path/Documents/page12.png",
    @"path/Documents/page6.png",
    @"path/Documents/page4.png",
    @"path/Documents/page5.png",
    @"path/Documents/page1.png",
    @"path/Documents/page7.png",
    @"path/Documents/page3.png",
    @"path/Documents/page2.png"];

如果我现在使用以下方法对数组进行排序:

[pathArray sortUsingSelector:@selector(caseInsensitiveCompare:)];

数组排序错误

结果:

pathArray: (
    "path/Documents/page0.png",
    "path/Documents/page1.png",
    "path/Documents/page10.png",
    "path/Documents/page11.png",
    "path/Documents/page12.png",
    "path/Documents/page2.png",
    "path/Documents/page3.png",
    "path/Documents/page4.png",
    "path/Documents/page5.png",
    "path/Documents/page6.png",
    "path/Documents/page7.png",
    "path/Documents/page8.png",
    "path/Documents/page9.png"}

带有组件的元素"page10.png", "page11.png" and "page12.png"应该是最后三个元素。是否存在涵盖此问题的另一个选择器?

如果不是,怎么可能做到这一点?

4

2 回答 2

4

您可以使用以下方法实现自己的比较方法:

[pathArray sortUsingComparator:^(id one, id two) {
    return [one compare:two options:NSCaseInsensitiveSearch | NSNumericSearch];
}
于 2013-11-14T12:04:20.630 回答
1

这是因为您的文件名不一致,例如:

path/Documents/page0.png

应该:

path/Documents/page00.png

其中每个文件都有一个 2 位数字。解决此问题后,您的排序将正常工作。

于 2013-11-14T12:00:29.350 回答