Sort an array of doubles or CLLocationDistance values ​​on iPhone

I am trying to sort the list of CLLocationDistance values ​​by the closest distance (ascending). First I converted the values ​​to NSString objects to use the following view:

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

NSString cannot sort a numeric value.

How to set the list of numerical values ​​in ascending order?

+4
source share
3 answers

I think you want sortedArrayUsingFunction:context: use 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]; 

link to apple documents

+8
source
+1
source

When you convert the values ​​into strings, the sorting will be lexicographic, not numeric, which does not match your question. CLLocationDistance defined as a double type according to Apple docs. With this in mind, create an NSArray with NSNumber instances initialized with your CLLocationDistance data (see numberWithDouble ) and use NSArray sorting compared to them.

Read more about NSNumber here .

0
source

All Articles