Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array of doubles or CLLocationDistance values on the iPhone

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?

like image 351
Atma Avatar asked Jan 23 '23 05:01

Atma


2 Answers

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

like image 99
slf Avatar answered May 04 '23 00:05

slf


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_Class/NSArray.html#//apple_ref/occ/instm/NSArray/sortedArrayUsingSelector:

like image 32
Daniel Avatar answered May 03 '23 22:05

Daniel