-1

How to sort an NSMutableArray numerically when it contains objects like follows:

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"P3",@"P1",@"P4",@"P10", nil];

The output of the same should be like: P1, P3, P4, P10

Bhargav Soni
  • 1,067
  • 1
  • 9
  • 22

4 Answers4

1

You need to use NSNumericSearch

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

From the Header Documentation-

NSNumericSearch = 64, /* Added in 10.2; Numbers within strings are compared using numeric value, that is, Foo2.txt < Foo7.txt < Foo25.txt; only applies to compare methods, not find */

Hope this is what you are looking for.

Tarun Tyagi
  • 9,364
  • 2
  • 17
  • 30
0

Assuming there is always a character at the start of the strings, then:

[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSInteger i1 = [[obj1 substringFromIndex:1] integerValue];
    NSInteger i2 = [[obj2 substringFromIndex:1] integerValue];
    if (i1 > i2)
        return NSOrderedDescending;
    else if (i1 < i2)
        return NSOrderedAscending;
    return NSOrderedSame;
}];
Droppy
  • 9,691
  • 1
  • 20
  • 27
0

try this code:

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"P3",@"P1",@"P4",@"P10", nil];

NSLog(@"Array: %@",array);
NSSortDescriptor *lastNameDescriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES selector:@selector(localizedStandardCompare:)];

NSArray *sorters = [[NSArray alloc] initWithObjects:lastNameDescriptor, nil];

NSArray *sortedArray = [array sortedArrayUsingDescriptors:sorters];

NSMutableArray *sortArray = [[NSMutableArray alloc] init];

[sortArray addObjectsFromArray:sortedArray];

NSLog(@"sortArray : %@",sortArray);

Output::

2016-06-15 16:47:47.707 test[5283:150858] Array: (
P3,
P1,
P4,
P10
)
2016-06-15 16:47:47.708 test[5283:150858] sortArray : (
P1,
P3,
P4,
P10
)
Bhadresh Kathiriya
  • 3,147
  • 2
  • 21
  • 41
-1

You can also sort NSArrayor NSMutableArray using NSSortDescriptor.

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES];
NSArray *sortedArray = [<arrayToBeSorted> sortedArrayUsingDescriptors:@[sd]];
NSLog(@"Result = %@", sortedArray);
Mahendra
  • 8,448
  • 3
  • 33
  • 56