如何按 Objective-C 中最后的数字按字母顺序对数组控制器进行排序?
我有一个 NSArrayController ,我想对内容进行排序,以便首先对包含英文字母的任何内容进行排序,然后对包含数字和非英文字符的任何内容进行最后排序。
例如:A,B,C ... Z,1,2,3 ... 9,구,결,...
目前我只知道如何按字母顺序对项目进行排序。建议?
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[dataController setSortDescriptors: [NSArray arrayWithObject: sort]];
I have an NSArrayController
and I would like to sort the contents so that anything with English alphabets are sorted first and then anything with numbers and non English characters are sorted last.
For example: A, B , C ... Z, 1 , 2, 3 ... 9, 구, 결, ...
Currently I only know how to sort items in alphabetical order. Suggestions?
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[dataController setSortDescriptors: [NSArray arrayWithObject: sort]];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
sortedArrayUsingComparator
根据您的需要自定义排序算法。例如,您可以使用以下行赋予符号优先级:要将英语字符放在非英语字符之前,使用
NSDiacriticInsensitiveSearch | 就足够了。 NSCaseInsensitiveSearch
作为选项,不需要花哨的算法。如果您需要支持没有块的 iOS,请尝试
sortedArrayUsingSelector
。You can use
sortedArrayUsingComparator
to customize the sort algorithm to your needs. For instance, you can give precedence to symbols with this lines:To put English characters before non-English ones, it'd be enough to use
NSDiacriticInsensitiveSearch | NSCaseInsensitiveSearch
as options, no fancy algorithm required.If you need to support iOS without blocks try
sortedArrayUsingSelector
.另一种解决方案是测试字符串是否可编码:
否则,如果一个以数字开头,一个以字母开头,则返回 NSOrderingAscending,如果以字母开头,则返回 NSOrderingAscending第一个,否则
NSOrderingDescending
如果两个字符串都不是拉丁字符串,则让
compare:
再次决定代码
结果
Another solution by testing, if a string is latin1-encodeable:
compare:
else, if one starts with the number and one with a letter,
return NSOrderingAscending
, if the one with letter its first, otherwiseNSOrderingDescending
If both strings aren't latin, let
compare:
decide againreturn NSOrderingAscending
if the latin is first, otherwiseNSOrderingDescending
the code
result
我认为如果不定义自己的比较函数就无法进行这种排序。
为此,您可以使用 sortedArrayUsingFunction:
其中 f 定义为:
如果您愿意不创建函数来执行此操作,您可以使用该方法的块版本 sortedArrayUsingComparator:
I don't think you can do that kind of sorting without defining your own comparison function.
To this aim, you could use sortedArrayUsingFunction:
where f is defined as:
If you prefer not creating function for doing this you could use the block-version of the method, sortedArrayUsingComparator:
基于比较器的排序描述符应该可以解决问题(注意:未经测试)。
您当然必须定义自己的排序顺序算法 - 但此示例应该展示如何使用数组控制器的排序描述符。
A sort descriptor based on a comparator should do the trick (note: not tested).
You of course have to define your own sort order algorithm - but this example should show how to use a sort descriptor for an array controller.
缺少一件事来正确回答这个问题:NSNumericSearch
One thing is missing to answer properly to the question : NSNumericSearch