0

why if i have this array named "keys":

( 950, 24889, 24893, 24694, 947, 13227, 23549, 37839, 951, 6213, 24892, 24897, 948, 37838, 30971, 952, 13249, 24891, 24896, 949, 37837, 24890, 945, 953, 24895, 23791, 37836, 24894, 946, 13228 )

and i sort it with:

NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(compare:)];

the sorted array sortedKeys is this?

( 13227, 13228, 13249, 23549, 23791, 24694, 24889, 24890, 24891, 24892, 24893, 24894, 24895, 24896, 24897, 30971, 37836, 37837, 37838, 37839, 6213, 945, 946, 947, 948, 949, 950, 951, 952, 953

it's not really sorted...

Frankie94
  • 55
  • 9

2 Answers2

5

Your keys appear to actually be NSString objects, not NSNumber objects. That means they sort lexicographically, not numerically.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
1

It appears that what Carl is saying is correct and you actually have an array full of string objects. The easiest way to sort these numerically if you know that they represent numbers is to sort on the intValue method of these objects.

An example of this would be:

NSArray *sortedKeys = [keys sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"intValue" ascending:YES]]];
Dima
  • 23,484
  • 6
  • 56
  • 83