2

I want to sort array using NSSortDescriptor.

Here is my code

 NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:@"filename"  ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
[arrDocuments sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];

What I get is this incorrect result.

  1. New Folder 1
  2. New Folder 11
  3. New Folder 12
  4. New Folder 2

Expected

  1. New Folder 1
  2. New Folder 2
  3. New Folder 11
  4. New Folder 12
2
  • You're using an alphabetic sort. You need an alpha-numeric sort. Commented Jul 18, 2013 at 9:17
  • New Folder is static for every file name ? Commented Jul 18, 2013 at 9:21

1 Answer 1

8

The function localizedCaseInsensitiveCompare: is an alphabetic search.

You would be better using a function like...

compare:options:

With the options NSNumericSearch this treats any numbers as numeric and so sorts them 1, 2, 10, etc...

alphabetically though 10 comes before 2 hence your problem.

The entire code would look like...

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"fileName" ascending:YES comparator:^(NSString *obj1, NSString *obj2) {

    return [obj1 compare:obj2 options:NSNumericSearch | NSCaseInsensitiveSearch];

}];

[arrDocuments sortUsingDescriptors:@[sd]];
Sign up to request clarification or add additional context in comments.

1 Comment

Great idea works on alpha numeric as well on the only alphabetic or only numeric. good one .thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.