Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Number using NSSortDescriptor

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.

like image 365
iOmi Avatar asked Dec 14 '12 07:12

iOmi


3 Answers

Try this:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:@"rank"  ascending:YES selector:@selector(localizedStandardCompare:)];
like image 161
Darshit Shah Avatar answered Nov 11 '22 15:11

Darshit Shah


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.

like image 26
Mundi Avatar answered Nov 11 '22 14:11

Mundi


[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

like image 3
Arsalan Avatar answered Nov 11 '22 14:11

Arsalan