开发者

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

开发者 https://www.devze.com 2023-04-08 20:09 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号