IOS: natural sort order

I have an iOS app that uses Core Data to save and retrieve data.
How to get data sorted by field of type NSString in natural sort order ?

Now the result is:

100_title
10_title
1_title

      

I need:

1_title
10_title
100_title

      

+3


source to share


1 answer


You can use localizedStandardCompare: as a selector in a sort descriptor to request a Core Data fetch like

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 subclass of the managed data object.

+6


source







All Articles