views:

836

answers:

3

I'm trying to sort a list of CLLocationDistance values by closest distance (ascending order). I first converted the values to NSString objects so that I could use the following sort:

NSArray *sortedArray;
sortedArray = [distances sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

NSString cannot sort on the numeric value.

How can I set a list of numeric values in ascending order?

+1  A: 

Try using sortedArrayUsingSelector where you define the function to compare the elements heres a reference :http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray%5FClass/NSArray.html#//apple%5Fref/occ/instm/NSArray/sortedArrayUsingSelector:

Daniel
+2  A: 

I think what you want is sortedArrayUsingFunction:context: using something like this:

NSInteger intSort(id num1, id num2, void *context)
{
    int v1 = [num1 intValue];
    int v2 = [num2 intValue];
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

// sort things
NSArray *sortedArray; sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];

apple docs reference

slf
A: 

When you convert the values to strings the sort will be lexicographical instead of numerical, which is not what you want according your question. CLLocationDistance is defined to be type double according to the Apple docs. Given that, create your NSArray with NSNumber instances initialized with your CLLocationDistance data (see numberWithDouble), and use NSArray's sorting implementation against those.

More on NSNumber is here.

fbrereto