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
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