iOmi
iOmi

Reputation: 635

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.

Upvotes: 5

Views: 5579

Answers (3)

Arsalan
Arsalan

Reputation: 31

[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

Upvotes: 3

Darshit Shah
Darshit Shah

Reputation: 2382

Try this:

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

Upvotes: 14

Mundi
Mundi

Reputation: 80271

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.

Upvotes: 3

Related Questions