iOS:自然排序 [英] iOS: natural sort order

查看:22
本文介绍了iOS:自然排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an app for iOS that uses Core Data to save and retrieve data.
How would I fetch data sorted by a field of NSString type in natural sort order?

现在的结果是:

100_title
10_title
1_title

我需要:

1_title
10_title
100_title

推荐答案

您可以使用 localizedStandardCompare: 作为核心数据获取请求的排序描述符中的选择器,例如

You can use localizedStandardCompare: as selector in the sort descriptor for the Core Data fetch request, for example

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

Swift 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 托管对象子类的名称.

where "Entity" is the name of the Core Data managed object subclass.

这篇关于iOS:自然排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆