Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array that contain alphanumeric words in iOS [duplicate]

I have a array with 10 elements called products which is sorted by default, this is the current log now.

for (int i=0;i<products.count; i++)
{
     NSLog(@"%@",products[i]);
}

The Output:

Product1
Product10
Product2
Product3
Product4
Product5
Product6
Product7
Product8
Product9

I need to sort it in following order:

Product1
Product2
Product3
Product4
Product5
Product6
Product7
Product8
Product9
Product10

My current method is to scan out the numbers and sort based on that, I was wondering if there is any other way or and default method in iOS that does this or should I have to stick with my current method of scanning the numbers in each element and then sort??

like image 777
Francis F Avatar asked Dec 24 '13 09:12

Francis F


1 Answers

You can use this code to sort array. Use NSNumericSearch to search the numeric value in string.

NSArray * products = [[NSArray alloc] initWithObjects:@"Product1",
                                                      @"Product10",
                                                      @"Product2",
                                                      @"Product3",
                                                      @"Product4",
                                                      @"Product5",
                                                      @"Product6",
                                                      @"Product7",
                                                      @"Product8",
                                                      @"Product9",
                                                      nil];

products = [products sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
    }];

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

And the log display :

products : (
    Product1,
    Product2,
    Product3,
    Product4,
    Product5,
    Product6,
    Product7,
    Product8,
    Product9,
    Product10
)
like image 96
Dilip Avatar answered Oct 25 '22 23:10

Dilip