Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone - sorting "10, 20, 30" the correct order with core data

I have a string field on an entity. Every time I want to retrieve a sort list of entries and the entries contain numbers, the list comes like this:

car 1
car 10
car 11
car 2
car 21
etc.

instead of

car 1
car 2
car 10
car 11
car 21

How do I force the request to sort the numbers correctly in a string property?

I am using this:

NSSortDescriptor *sortByItem =  [NSSortDescriptor sortDescriptorWithKey:key ascending:YES selector:@selector(compare:)];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByItem];
[request setSortDescriptors:sortDescriptors];

thanks.

like image 751
Duck Avatar asked Dec 30 '25 07:12

Duck


2 Answers

Write your own comparison method that looks like this:

- (NSComparisonResult)numericCompare:(NSString *)aString
{
    return [self compare:aString options:NSNumericSearch];
}

Then pass this method's selector to the sort descriptor.

like image 132
Ole Begemann Avatar answered Jan 01 '26 21:01

Ole Begemann


I have found an easier way. Simply use localizedStandardCompare: instead of compare: and it sorts numbers on strings correctly.

like image 44
Duck Avatar answered Jan 01 '26 22:01

Duck