Sorting Number using NSSortDescriptor

扶醉桌前 提交于 2019-12-07 05:28:23

问题


I got stuck in another problem again but after a long time.

This time I have database (Core Data), having an attribute of numbers which contains integer numbers like 213879,123,4,345,56567 and so.

I need to fetch data in ascending number order similar to like alphabetically order.

I am doing this in way given below,

fetchRequest.sortDescriptors=[NSArray arrayWithObject:
      [NSSortDescriptor sortDescriptorWithKey:@"numbers" 
                                    ascending:YES 
                                     selector:@selector(compare:)]];

but unfortunately it compares only the 1st digit of every number, mean if there are 2 numbers like 123 and 321, it will compare 1 (first digit of first number) with 3 (first digit of second number) and sort them.

It got confuse when there comes 123 and 111 (same first digits of all numbers).

If I am doing something wrong or the SortDescriptor works in this way? I need the solution to sort the numbers in ascending 123,133,213,451,516 likewise.

Thing to Remember In actual the attribute numbers will contains integer numbers having digits more then 6. e.g 1234567,234568,235481

Thanks to all who helps me a lot in anticipation.


回答1:


It seems your attribute is of type NSString. Make sure you make it to NSNumber, the sorting will then work as expected.

There is no need to selector:@selector(compare:) in your sort descriptor as this is the default anyway.




回答2:


Try this:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:@"rank"  ascending:YES selector:@selector(localizedStandardCompare:)];



回答3:


[NSSortDescriptor sortDescriptorWithKey:@"self"
                              ascending:YES
                             comparator:^(id obj1, id obj2){
    return [(NSString*)obj1 compare:(NSString*)obj2
                            options:NSNumericSearch];
 }];

this is working fine for me perfect



来源:https://stackoverflow.com/questions/13874256/sorting-number-using-nssortdescriptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!