简体   繁体   中英

Sorting array(NSString + Number) using NSSortDescriptor in IOS?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM