views:

149

answers:

2

Hi all, I got an array in my app and I need to order by one of its key.

Basically what the app does is taking latitude and longitude somewhere, calculate the distance from my actual position and create an array containing a key called "distance".

I'm using

myArray sortUsingDescriptors:
    [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES] autorelease]]];

I'm not sure it's working, I mean the first results are ordered but then it shows distance closer to the previous, as example:

0.8 km
1.6 km
1.9 km
10053.9 km
1098.0 km
2372.0 km
470.5 km

Any suggestion?

I thank you in advance for any kind of help.

Fabrizio

+4  A: 

That looks like a valid ordering - if your distance value is a string. To get a numeric ordering you should save it as a NSNumber.

Paul Lynch
Did you mean save it as a NSNumber inside the array? I'm not quite sure I've understood. Btw thanx.
Fabrizio
Ok fixed, thank you very much.
Fabrizio
A: 

You should be able to use a custom sorting function that respects numerical values.

(I'm now assuming the "distance" key of your objects is a NSString

static NSInteger numericCompare(id first, id second, void* context)
{
    return [(NSString*)[first distance] compare:[second distance] options:NSCaseInsensitiveSearch | NSNumericSearch];
}

Now you can get your sorted array using the sort method in NSArray

NSArray* sortedArray = [myArray sortedArrayUsingFunction:numericCompare context:NULL];
alleus