Home > DeveloperSection > Forums > How to sort alphanumeric word in array in ios?
Ankita Pandey
Ankita Pandey

Total Post:183

Points:1285
Posted on    November-11-2014 10:40 PM

 iPhone Ios  Objective C  Sorting 
Ratings:


 1 Reply(s)
 704  View(s)
Rate this:

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



Royce Roy
Royce Roy

Total Post:134

Points:938
Posted on    November-12-2014 2:39 AM

You can use this code to sort array. Use  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

)


Don't want to miss updates? Please click the below button!

Follow MindStick