PDA

View Full Version : sortedArrayUsingSelector problem




spaceman816
Aug 2, 2009, 05:31 PM
I have a plist eastDict- I'm trying to make the keys into a sorted array but for some reason it's sorting incorrectly. The keys are: 1, 50, 100, 150, 200, 300, 400, 500.
I sorted the keys into an array like this:
NSArray *ranges = [[eastDict allKeys] sortedArrayUsingSelector: @selector(compare: )];

I eventually realized there was something wrong with the array, and so I looped through it and found that the keys were sorted as follows: 1, 100, 150, 200, 300, 400, 50, 500.

I have no clue as to why this would be.



gnasher729
Aug 2, 2009, 05:43 PM
I have a plist eastDict- I'm trying to make the keys into a sorted array but for some reason it's sorting incorrectly. The keys are: 1, 50, 100, 150, 200, 300, 400, 500.
I sorted the keys into an array like this:
NSArray *ranges = [[eastDict allKeys] sortedArrayUsingSelector: @selector(compare: )];

I eventually realized there was something wrong with the array, and so I looped through it and found that the keys were sorted as follows: 1, 100, 150, 200, 300, 400, 50, 500.

I have no clue as to why this would be.

What happens when you compare the NSString* @"100" and @"50" using compare: ?

spaceman816
Aug 2, 2009, 05:58 PM
What happens when you compare the NSString* @"100" and @"50" using compare: ?

[@"100" compare:@"50"] returns -1

robbieduncan
Aug 2, 2009, 06:02 PM
Probably because it's comparing them as strings, not as numbers. So most likely it looks at the first character off each string. If they are the same then the second, otherwise it returns based on that character. So in character (and integer) comparison 1<5 so @"100" < @"50".

Implement your own comparison selector that converts the strings to numbers and compares them as numbers.

lee1210
Aug 2, 2009, 06:41 PM
Others have pointed out the issue, which is lexical vs. numerical comparison. NSString's compare: ultimately calls:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/compare:options:range:locale:

It is explicitly noted there that lexical comparison is done.

Just adding this info to help you help yourself. Between this and your prior post, it looks like some time in the docs would be helpful.

-Lee

ghayenga
Aug 2, 2009, 09:19 PM
I have a plist eastDict- I'm trying to make the keys into a sorted array but for some reason it's sorting incorrectly. The keys are: 1, 50, 100, 150, 200, 300, 400, 500.
I sorted the keys into an array like this:
NSArray *ranges = [[eastDict allKeys] sortedArrayUsingSelector: @selector(compare: )];

I eventually realized there was something wrong with the array, and so I looped through it and found that the keys were sorted as follows: 1, 100, 150, 200, 300, 400, 50, 500.

I have no clue as to why this would be.

Because it's sorting them as strings.