iOS: natural sort order

*爱你&永不变心* 提交于 2019-11-27 08:19:50

问题


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?

Right now the result is:

100_title
10_title
1_title

I need:

1_title
10_title
100_title

回答1:


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]

or better

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

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



来源:https://stackoverflow.com/questions/14604503/ios-natural-sort-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!