【问题标题】:iOS: natural sort orderiOS:自然排序顺序
【发布时间】:2013-01-30 12:52:42
【问题描述】:

我有一个 iOS 应用,它使用 Core Data 来保存和检索数据。
如何获取按自然排序顺序的 NSString 类型字段排序的数据?

现在的结果是:

100_title
10_title
1_title

我需要:

1_title
10_title
100_title

【问题讨论】:

  • 看看this question
  • @dandan78 非常感谢。但是 iOS 的 Core Data 不支持比较器。 “NSSortDescriptor(不支持比较器块)”。有没有办法给 Core Data 一个提示,用 NSNumericSearch 标志对字段进行排序?
  • @surlac:看看 Peter Hosey 对该问题的回答:您可以在核心数据排序描述符中使用 localizedStandardCompare:
  • @MartinR,你太棒了!我添加了localizedStandardCompare: 选择器,它现在以自然方式排序。非常感谢你!请把它放在一个单独的答案中,以便我标记它。我认为将 SO 作为上述问题的 iOS 版本本地化会有所帮助。

标签: ios core-data nsfetchrequest natural-sort


【解决方案1】:

你可以使用localizedStandardCompare:作为Core Data获取请求的排序描述符中的选择器,例如

NSSortDescriptor *titleSort = [[NSSortDescriptor alloc] initWithKey:@"title"
                                  ascending:YES 
                                   selector:@selector(localizedStandardCompare:)];
[fetchRequest setSortDescriptors:[titleSort]];

斯威夫特 3:

let titleSort = NSSortDescriptor(key: "title",
                    ascending: true,
                    selector: #selector(NSString.localizedStandardCompare))
fetchRequest.sortDescriptors = [sortDescriptor]

或更好

let titleSort = NSSortDescriptor(key: #keyPath(Entity.title),
                    ascending: true,
                    selector: #selector(NSString.localizedStandardCompare))
fetchRequest.sortDescriptors = [sortDescriptor]

其中“Entity”是 Core Data 托管对象子类的名称。

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    相关资源
    最近更新 更多