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.
Try this:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:@"rank" ascending:YES selector:@selector(localizedStandardCompare:)];
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.
[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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With