Search code examples
iosobjective-csortingnsmutablearraynsarray

Sorting NSMutableArray Removing First Element


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


Solution

  • 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.