Sort array that contain alphanumeric words in iOS

2 Solutions Collect From Internet About “Sort array that contain alphanumeric words in iOS”

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
)
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc]initWithKey:@"YourKeyName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];


self.products = [[self.products sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sortDesc, nil]] mutableCopy];

For more details Apple Documentation