1

Here's the problem i have :- I have an array

Item1,
Item2,
Item3,
Item4,
Item5,
Item6,
Item7,
....,Item11

I need to sort this array in that specific order ,ofcourse all the values are of type 'NSString'

if i use

sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)

it sorts it like this:-

Item1,
Item10,
Item11,
Item2,
Item3,
Item4,
Item5,
Item6,
Item7,
Item8,
Item9

I can manually extract the numeric value from this but i thought there may be a better way to do this perhaps by using 'NSComparator'.

Aatish Molasi
  • 2,138
  • 3
  • 20
  • 43
  • possible duplicate of [How to do a natural sort on an NSArray?](http://stackoverflow.com/questions/2846301/how-to-do-a-natural-sort-on-an-nsarray) – Aravindhan Jul 10 '12 at 06:39

5 Answers5

2

Use it like this:

NSArray *arry = [[NSArray alloc] initWithObjects:@"Item1",@"Item2",@"Item3",@"Item4",@"Item5",@"Item11",@"Item10",@"Item6", nil];
NSArray *sortedStrings = [arry sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
NSLog(@"sortedStrings---%@",sortedStrings);
Rui Peres
  • 25,741
  • 9
  • 87
  • 137
Narayana Rao Routhu
  • 6,303
  • 27
  • 42
1
NSInteger sortFile(id a, id b, void* context) {
    return [a compare:b options:NSNumericSearch];
}

[yourArray sortedArrayUsingFunction:mySort context:nil];
msk
  • 8,885
  • 6
  • 41
  • 72
1

This code works for me:

NSArray *array = [NSArray arrayWithObjects:@"Item1",
                  @"Item10",
                  @"Item11",
                  @"Item2",
                  @"Item3", nil];

array = [array sortedArrayUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
    return [str1 compare:str2 options:(NSNumericSearch)];
} ];

NSLog(@"%@", array);
Adam
  • 26,549
  • 8
  • 62
  • 79
0

Try this:

 NSArray *sortedStrings = [yourArray sortedArrayUsingSelector:@selector(localizedStandardCompare:)];

For more sortedArrayUsingSelector

Ravi Kumar Karunanithi
  • 2,151
  • 2
  • 19
  • 41
0

You can implement whatever function you want if you do it using sortedArrayUsingFunction:context:

borrrden
  • 33,256
  • 8
  • 74
  • 109