iphone - 如何自定义 NSArray 字符串的排序顺序?

标签 iphone objective-c ios nsstring 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

如何自定义排序行为以提供此排序?

最佳答案

sortedArrayUsingSelector: 告诉数组询问它尝试排序的各个对象的适当排序顺序。要提供您自己的,请使用其他 sortedArrayUsing... 函数之一。最简单的任务可能是 sortedArrayUsingFunction:context:它允许您指定一个普通的旧 C 函数来进行比较。

另一种方法是使用类别向 NSString 类添加排序功能,类似于 compareInMyFavor: 并将其作为选择器传递给 sortedArrayUsingSelector:.

现在我想到了,后者可能是更清洁的解决方案。你来电。

关于iphone - 如何自定义 NSArray 字符串的排序顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6817901/

相关文章:

iphone - 无法摆脱继承的委托(delegate)方法警告

iphone - 更改 UILabel 文本会弄乱动画吗?

iphone - 如何在没有导航 Controller 的情况下创建多个 View ?

iPhone:在 UIScrollView 或 UITableView 上覆盖图像

objective-c - 拖动 UIImages 到选中区域

ios - 如何更新 iPhone App 中的 ApplicationBadgeIcon?

javascript - iPhone UIWebView getElementsByClassName

objective-c - 如果不删除其他对象的观察者,KVO 会导致循环

ios - 原生 iOS 国家/地区选择器

ios - 作为其他 MOC 的子项创建的 MOC 是否也会包含未保存的更改?