Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

Lets suppose I have an array like this

NSArray* arr = @[@"1",@"4",@"2",@"8",@"11",@"10",@"14",@"9"]; //note: strings containing numbers

and I want to sort them like this: [1,2,4,8,9,10,11,14]

but if I use

[arr sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

I get [1,10,11,14,2,4,8,9]... and if I use:

   NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:YES];
   NSArray *sortDescriptors = @[sortDescriptor];
   [arr sortedArrayUsingDescriptors:sortDescriptors];

I get something like this: [1,4,2,8,9,11,10,14]

How can I combine both predicates? or is any other easier way to solve this? note: The output of this array is merely for debug purposes, I dont care if the result turns the array into integers as long as I can print in console with NSLog thanks

share|improve this question

marked as duplicate by Josh Caswell Jun 20 '14 at 19:18

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
actually it would be better a function that returns the numbers missing between the min and the max value... example input: [1,5,4]... output:[2,3] –  user2387149 Jun 20 '14 at 16:23

2 Answers 2

up vote 2 down vote accepted

Try using blocks

[arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    if ([obj1 intValue]==[obj2 intValue])
        return NSOrderedSame;

    else if ([obj1 intValue]<[obj2 intValue])
        return NSOrderedAscending;
    else
        return NSOrderedDescending;

}];
share|improve this answer
    
thanks pal, I just had to change the ">" for "<" –  user2387149 Jun 20 '14 at 16:41
    
oh sorry my bad. I updated the answer. –  cekisakurek Jun 20 '14 at 18:01
3  
The important part of this answer is lost in the minimal explanation. You can sort using blocks or sort descriptors -- it's not blocks that make the difference here. The important thing is to use -intValue rather than trying to combine -length and -localizedCaseInsensitiveCompare:. –  Caleb Jun 20 '14 at 18:09

The problem is that you're trying to use both string comparison and -length to cobble together what you really want, which is numeric comparison. But sort descriptors are applied one at a time, and a second descriptor is only used if the first one orders two items as the same. Using -intValue to order the items lets you use a single sort descriptor that will order the items the way you want.

Do this instead:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"intValue" ascending:YES];
[arr sortedArrayUsingDescriptors:@[sortDescriptor]];
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.