sortedArrayUsingSelector problem

Discussion in 'Mac Programming' started by spaceman816, Aug 2, 2009.

  1. spaceman816 macrumors member

    Joined:
    Jul 29, 2009
    #1
    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:
    Code:
    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.
     
  2. gnasher729 macrumors P6

    gnasher729

    Joined:
    Nov 25, 2005
    #2
    What happens when you compare the NSString* @"100" and @"50" using compare: ?
     
  3. spaceman816 thread starter macrumors member

    Joined:
    Jul 29, 2009
    #3
    [@"100" compare:mad:"50"] returns -1
     
  4. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #4
    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.
     
  5. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #5
  6. ghayenga macrumors regular

    Joined:
    Jun 18, 2008
    #6
    Because it's sorting them as strings.
     

Share This Page