如何自定义 NSArray 字符串的排序顺序?
我有一系列代表以下文件名的字符串:hello1(eng).txt
、hello1(por).txt
、hello1.txt
。当我使用
NSArray *array = [filePaths sortedArrayUsingSelector: @selector(compare:)];
返回的顺序对它们进行排序时,返回的顺序是 hello1(eng).txt, hello1(por).txt, hello1.txt
。相反,我希望按此顺序,最后返回括号中的项目:hello1.txt、hello1(eng).txt、hello1(por).txt
。
如何自定义排序行为以提供此排序?
I have a series of strings representing the following file names: hello1(eng).txt
, hello1(por).txt
, hello1.txt
. When I sort them using
NSArray *array = [filePaths sortedArrayUsingSelector: @selector(compare:)];
The order returned is hello1(eng).txt, hello1(por).txt, hello1.txt
. I would instead like to have this order, where the items in parentheses are returned last: hello1.txt, hello1(eng).txt, hello1(por).txt
.
How can I customize the sorting behavior to provide this ordering?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
sortedArrayUsingSelector:
告诉数组询问它尝试排序的各个对象是否具有适当的排序顺序。要提供您自己的函数,请使用其他sortedArrayUsing...
函数之一。最简单的任务可能是 sortedArrayUsingFunction:context: 允许您指定一个普通的旧版本进行比较的 C 函数。另一种方法是使用类别向 NSString 类添加排序函数,类似于compareInMyFavor:,并将其作为
sortedArrayUsingSelector:
的选择器传递。现在我想起来,后者可能是更干净的解决方案。你的电话。
sortedArrayUsingSelector:
tells the array to ask the individual objects it's trying to sort for the appropriate sort order. To provide your own, use one of the othersortedArrayUsing…
functions. The easiest for your task is probably sortedArrayUsingFunction:context: which allows you to specify a plain old C function which does the comparison.Another approach would be to use a category to add a sorting function to the NSString class, something along the lines of
compareInMyFavor:
and pass that as the selector forsortedArrayUsingSelector:
.Now that I think of it, the latter is probably the cleaner solution. Your call.