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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With