Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: natural sort order

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
like image 524
surlac Avatar asked Dec 26 '22 10:12

surlac


1 Answers

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.

like image 74
Martin R Avatar answered Jan 05 '23 23:01

Martin R