sur*_*lac 3 core-data natural-sort nsfetchrequest ios
我有一个iOS应用程序,它使用Core Data来保存和检索数据.
如何按自然排序顺序获取按NSString类型字段排序的数据?
现在的结果是:
100_title
10_title
1_title
Run Code Online (Sandbox Code Playgroud)
我需要:
1_title
10_title
100_title
Run Code Online (Sandbox Code Playgroud)
例如,您可以使用localizedStandardCompare:作为核心数据获取请求的排序描述符中的选择器
NSSortDescriptor *titleSort = [[NSSortDescriptor alloc] initWithKey:@"title"
ascending:YES
selector:@selector(localizedStandardCompare:)];
[fetchRequest setSortDescriptors:[titleSort]];
Run Code Online (Sandbox Code Playgroud)
斯威夫特3:
let titleSort = NSSortDescriptor(key: "title",
ascending: true,
selector: #selector(NSString.localizedStandardCompare))
fetchRequest.sortDescriptors = [sortDescriptor]
Run Code Online (Sandbox Code Playgroud)
或更好
let titleSort = NSSortDescriptor(key: #keyPath(Entity.title),
ascending: true,
selector: #selector(NSString.localizedStandardCompare))
fetchRequest.sortDescriptors = [sortDescriptor]
Run Code Online (Sandbox Code Playgroud)
其中"Entity"是Core Data托管对象子类的名称.