3

So i have the following code:

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"];

If I now sort the array using:

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

The Array is sorted the wrong way

Result:

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"}

The elements with the components "page10.png", "page11.png" and "page12.png" should be the last three elements. Does another selector exist that covers this issue?

If not how could this be done?

pmk
  • 1,897
  • 2
  • 21
  • 34
  • Or [I have an NSArray on NSString's, but some of the strings are only numbers. How do I sort numerically properly?](http://stackoverflow.com/questions/7375561/i-have-an-nsarray-on-nsstrings-but-some-of-the-strings-are-only-numbers-how-d), [How to do a natural sort on an NSArray?](http://stackoverflow.com/questions/2846301/how-to-do-a-natural-sort-on-an-nsarray) – Martin R Nov 14 '13 at 12:24

2 Answers2

4

You can implement your own comparing method using this:

[pathArray sortUsingComparator:^(id one, id two) {
    return [one compare:two options:NSCaseInsensitiveSearch | NSNumericSearch];
}
Antonio MG
  • 20,382
  • 3
  • 43
  • 62
1

It's because of the inconsistency with your filenames, for example:

path/Documents/page0.png

should be:

path/Documents/page00.png

where every file has a 2-digit number. Once you fix this, your sorting will work fine.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • I dont think the solution should come from changing the file name, he may not be able to do it – Antonio MG Nov 14 '13 at 12:07
  • @AntonioMG It depends on what the restrictions are. If this was my project then I would be more consistent. If the filenames cannot be changed, however, I like your answer much better. – trojanfoe Nov 14 '13 at 12:08
  • your answer is correct too, I did not know this would save the issue. – pmk Nov 14 '13 at 12:19
  • @pmk It depends on how many of these files you have to sort, but I've just tested with 1,000,000 objects formatted like this and your original sort goes significantly faster (your original method is `first` and `NSNumericSearch` method is `second`): `first=0.340271, second=2.776139` – trojanfoe Nov 14 '13 at 12:27