4

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
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
surlac
  • 2,961
  • 2
  • 22
  • 31
  • 2
    Have a look at [this question](http://stackoverflow.com/questions/2846301/how-to-do-a-natural-sort-on-an-nsarray). – dandan78 Jan 30 '13 at 12:55
  • @dandan78 thanks a lot. But Comparators not supported on Core Data for iOS. "NSSortDescriptor (comparator blocks are not supported)". Is there a way to give Core Data a hint to sort a field with NSNumericSearch flag? – surlac Jan 30 '13 at 13:06
  • @surlac: Have a look at Peter Hosey's answer to that question: You can use `localizedStandardCompare:` in the Core Data sort descriptor. – Martin R Jan 30 '13 at 13:09
  • @MartinR, you rock! I've added `localizedStandardCompare:` selector and it is sorted natural way now. Thank you very much! Please put it in a separate answer so I can mark it. I think it would be helpful for SO as a localized for iOS version of the question mentioned above. – surlac Jan 30 '13 at 13:19

1 Answers1

10

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382