Abhinav
Abhinav

Reputation: 191

Sorting is not working correctly

I am saving some files in document directory through my app using custom naming as "file1.format" ,"file2.format" and so on.Later I fetch these files in an Array and printing them in a loop then they are coming in sorted form but the problem arises when I store "file10.format" and so on. After this the result comes is some what unexpected. As after saving 10th file the output comes like

file1.foramt file10.format file2.format . . file6.format file61.format file7.format I don't know why sorting take all 1s or 2s on one place as shown above while it is expected that 10 should just comes after 9 not after 1.I used all kind of sorting but the result is coming same all time.

Upvotes: 1

Views: 288

Answers (3)

Martin R
Martin R

Reputation: 539685

If you want to sort file names "as the Finder does", use localizedStandardCompare. In particular, numbers in the strings are sorted according to their numeric value:

NSArray *files = [NSArray arrayWithObjects:@"file10.format", @"file2.format", @"file1.format", nil];
NSArray *sorted = [files sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
NSLog(@"%@", sorted);

Output:

2012-11-05 11:38:55.474 test77[533:403] (
    "file1.format",
    "file2.format",
    "file10.format"
)

Upvotes: 2

Hermann Klecker
Hermann Klecker

Reputation: 14068

If you want to go with the regular string sorting sequence, then you should consider renaming your files. file00001.format, file00002.format and so on. In that case file00010.format follows file00009.format and file00011.format comes next

Upvotes: 1

Brian Willis
Brian Willis

Reputation: 23854

It is actually working correctly.

file10.format

Comes before

file2.format 

because the character 0 is seen as less than the character . which it's being compared to (both characters are in the same place in their respective file names.

In fact, back in the day, before you young people with your fancy graphical operating systems, this is how the filesystem sorted files too. </old man rant>

Upvotes: 0

Related Questions