Sort an array containing alphanumeric words in iOS

I have an array with 10 elements called products that are sorted by default, this is the current log.

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

Exit:

 Product1 Product10 Product2 Product3 Product4 Product5 Product6 Product7 Product8 Product9 

I need to sort it in the following order:

 Product1 Product2 Product3 Product4 Product5 Product6 Product7 Product8 Product9 Product10 

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

+8
sorting ios objective-c iphone nssortdescriptor
source share
2 answers

You can use this code to sort the array. Use NSNumericSearch to search for a numeric value in a 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 log display:

 products : ( Product1, Product2, Product3, Product4, Product5, Product6, Product7, Product8, Product9, Product10 ) 
+16
source share
 NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc]initWithKey:@"YourKeyName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]; self.products = [[self.products sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sortDesc, nil]] mutableCopy]; 

More Apple Documentation

-one
source share

All Articles