0

I am using the method [myArray sortedArrayUsingSelector:@selector(compare:)] with an NSArray that contains a lot of numbers.

When I don't use this function they get printed as:

99,
161,
278,
179,
180,
189,
182,
125

As you can see they are not ordered.

And when I actually use the function, they get printed as:

125,
161,
179,
180,
182,
189,
278,
99

They are ordered now, but the problem here is that the 99 stays at the end! Any idea of why this is happening?

jscs
  • 63,694
  • 13
  • 151
  • 195
Charls Pico
  • 61
  • 2
  • 9
  • 1
    http://stackoverflow.com/questions/2752992/how-to-let-the-sortedarrayusingselector-using-integer-to-sort-instead-of-string – SpaceDust__ Mar 25 '15 at 20:56
  • 1
    Your array does not contain numbers. It contains strings. Big difference. – rmaddy Mar 25 '15 at 21:05
  • So, how does it ordered all the numbers? Except the 99 of course. – Charls Pico Mar 25 '15 at 21:13
  • Because all of your strings are 3 characters (except the 99). If you had `099` it would sort correctly. But not because they are numbers but because the character "2" comes after "1", etc. – rmaddy Mar 25 '15 at 21:24
  • So, you are telling me that when the number reaches 4 characters, it will be first that the ones with 3 characters? like: 1000, 998, 999...? instead of: 998, 999, 1000? – Charls Pico Mar 25 '15 at 21:55
  • "1000" will appear before any string that begins with a 2-9 and even strings like "11". You need to understand the difference between sorting an actual number (`NSNumber') and a string ('NSString'). Strings are simply sorted alphabetically based on the Unicode value of each character in the string. Unless you use special sort options to treat the strings as numbers. – rmaddy Mar 26 '15 at 00:17
  • But since I am using the `[myArray sortedArrayUsingSelector:@selector(compare:)]` method, if you check the documentation, it actually compares a `NSNumber` not a `NSString`, so it must mean that my `NSArray` contains `NSNumber`s not `NSString`s. Am I right? – Charls Pico Mar 26 '15 at 01:13
  • No. `sortedArrayUsingSelector:` uses the provided selector against whatever objects are in the array. Many classes support the `compare:` method including `NSString`. If your array actually had `NSNumber` objects then they would sort as expected. Your output clearly indicates that you have `NSString` objects in your array. – rmaddy Mar 26 '15 at 02:26
  • I've just changed the `NSString` to `NSNumber` so now the `NSArray` contains `NSNumber`s, but it still makes the same error when applying the function. – Charls Pico Mar 26 '15 at 16:41
  • A more powerful way of sorting a list of NSString to use things like NSNumericSearch : NSArray *sortedArrayOfString = [arrayOfString sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch]; }]; – Tanuj Mar 27 '15 at 07:33

0 Answers0