iOmi iOmi - 4 months ago 11
Objective-C Question

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.

Answer

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.

Comments