Sort an array with strings containing numbers

Possible duplicate:
Sort NSString values ​​as NSInteger using NSSortDescriptor

I have an array that I populate with my NSMutableDictionary .. and I use this:

myArray =[[myDict allKeys]sortedArrayUsingSelector:@selector(IDONTKNOW:)]; 

AllKeys myDicts are NSStrings ... e.g. 123.423 or 423.343 ... I need to sort the new myArray by incremental numbers. 12.234 45.3343 522.533 5432.66 etc.

What do you need to insert in @selector to do it right? Thanks

+6
source share
3 answers

You can use NSSortDescriptor and pass doubleValue as a key.

 //sfloats would be your [myDict allKeys] NSArray *sfloats = @[ @"192.5235", @"235.4362", @"3.235", @"500.235", @"219.72" ]; NSArray *myArray = [sfloats sortedArrayUsingDescriptors: @[[NSSortDescriptor sortDescriptorWithKey:@"doubleValue" ascending:YES]]]; NSLog(@"Sorted: %@", myArray); 
+20
source

You cannot use sortedArrayUsingSelector: Use sortedArrayUsingComparator: and implement the comparison block yourself.

It looks like q / a:

Changing the sort order - [NSArray sortedArrayUsingComparator:]

(Actually this question code can be copied / pasted into your code and it will β€œjust work” as soon as you change it from integerValue to doubleValue for four calls with converting a string to a number):

 NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) { double n1 = [obj1 doubleValue]; double n2 = [obj2 doubleValue]; if (n1 > n2) { return (NSComparisonResult)NSOrderedDescending; } if (n1 < n2) { return (NSComparisonResult)NSOrderedAscending; } return (NSComparisonResult)NSOrderedSame; }]; 
+5
source

Consider sortedArrayUsingFunction: This allows you to define a custom comparison function to use when comparing items.

 myArray =[[myDict allKeys]sortedArrayUsingFunction:SortAsNumbers context:self]; NSInteger SortAsNumbers(id id1, id id2, void *context) { float v1 = [id1 floatValue]; float v2 = [id2 floatValue]; if (v1 < v2) { return NSOrderedAscending; } else if (v1 > v2) { return NSOrderedDescending; } return NSOrderedSame; } 

More information is available here: Sort NSArray using sortedArrayUsingFunction

0
source

All Articles