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.
- New Folder 1
- New Folder 11
- New Folder 12
- New Folder 2
Expected
- New Folder 1
- New Folder 2
- New Folder 11
- 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.