objective-C, sort an array of strings containing numbers

user2387149 picture user2387149 · Jun 20, 2014 · Viewed 7.1k times · Source

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

Answer

cekisakurek picture cekisakurek · Jun 20, 2014

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;

}];