0

I want to sort NSMutableArray which have NSInteger values inside. I tried to use this solution:

 NSArray *sorted = [array sortedArrayUsingSelector:@selector(compare:)];

It almost worked, so i want to ask why not everything alright with it. Here is example of data:

not sorted = (
    30,
    42,
    54,
    6,
    18
)

 sorted = (
    18,
    30,
    42,
    54,
    6
)

We can see that it sorted everything but 6 value which is at the end off array.

Why this could happened ?

Thank you.

Full method:

- (void) initialize{
    NSInteger min = 30;
    NSInteger interval = 12;
    NSInteger count = floor(60/interval);

    for (int i = 0; i < count; i++) {

        [array addObject:[NSString stringWithFormat:@"%i",min]];
        min +=interval;

        if (min > 60)
            min -= 60;
    }

    //DLog(@"not sorted = %@",minutes);
    array = [[array sortedArrayUsingSelector:@selector(compare:)] mutableCopy];
    //DLog(@"sorted = %@",minutes);

}
Streetboy
  • 4,351
  • 12
  • 56
  • 101
  • What did you do with array? I can get the right result in my Mac. 2012-12-18 16:16:12.936 Untitled[10001:707] ( 30, 42, 54, 6, 18 ) 2012-12-18 16:16:12.938 Untitled[10001:707] ( 6, 18, 30, 42, 54 ) – onevcat Dec 18 '12 at 07:17
  • 1
    have a look here http://stackoverflow.com/questions/2752992/how-to-let-the-sortedarrayusingselector-using-integer-to-sort-instead-of-string – CRDave Dec 18 '12 at 07:21
  • How did you wrap NSIntegers? Are they wrapped in NSStrings, NSValues or NSNumbers? – ksh Dec 18 '12 at 07:22
  • Added full method. Wrapped in NSStrings – Streetboy Dec 18 '12 at 07:27

1 Answers1

1

You are getting problem in above case because you are sorting string values not a NSNUMBER. You have to use NSNumber to add objects of integer. Then do something like:

      NSMutableArray *array = [[NSMutableArray alloc ] initWithObjects:
                              [NSNumber numberWithInt:10],    
                              [NSNumber numberWithInt:50],
                              [NSNumber numberWithInt:5],
                              [NSNumber numberWithInt:3],
                              nil];

      NSLog(@"SORTED = %@",[array sortedArrayUsingSelector:@selector(compare:
                                                               )]);

This will give you a sorted array.

Sham
  • 475
  • 2
  • 7