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 reque开发者_如何学Gost 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.
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.
I have found an easier way. Simply use localizedStandardCompare: instead of compare: and it sorts numbers on strings correctly.
精彩评论