在IOS中使用NSSortDescriptor对数组(NSString + Number)进行排序? [英] Sorting array(NSString + Number) using NSSortDescriptor in IOS?
问题描述
我想使用 NSSortDescriptor
对数组进行排序。
这是我的代码
NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:@filename升序:YES选择器:@selector(localizedCaseInsensitiveCompare :)];
[arrDocuments sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
我得到的是这个错误的结果。
< blockquote>
- 新文件夹1
- 新文件夹11
- 新文件夹12
- 新文件夹2
预期
- 新文件夹1
- 新文件夹2
- 新文件夹11
- 新文件夹12
函数 localizedCaseInsensitiveCompare:
是字母搜索。
你最好使用像......这样的函数。
compare:options:
使用选项 NSNumericSearch
这会将任何数字视为数字,因此将它们排序为1,2 ,10等等......
按字母顺序排列,但10来自2,因此你的问题。
整个代码看起来像......
NSSortDescriptor * sd = [NSSortDescriptor sortDescriptorWithKey:@fileName升序:是比较器:^(NSString * obj1,NSString * obj2){
return [obj1 compare:obj2 options:NSNumericSearch | NSCaseInsensitiveSearch];
}];
[arrDocuments sortUsingDescriptors:@ [sd]];
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]];
这篇关于在IOS中使用NSSortDescriptor对数组(NSString + Number)进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!