0

I have an array of strings that contain numbers i.e. Shift 1 RT9909 I sort the array as follows:

NSSet *forms = dataObject.rtForms;

NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"type" ascending:YES];
NSArray *sorted = [forms sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameDescriptor]];

This works fine while the number of elements is under 10. After this point Shift 10 RT9909 is placed in front Shift 2 RT9909.

So my question is how can I sort the array so that Shift 10 RT9909 would follow Shift 9 RT9909

2
  • 1
    You will have to parse the string into values and sort by those values. There is no way around it. Or add leading zeros to your strings. Commented Mar 29, 2017 at 14:34
  • 1
    NSArray *sorted = [forms sortedArrayUsingComparator:^NSComparisonResult(rtFormClass _Nonnull form1, rtFormClass * _Nonnull form2) { return [form1.type compare:form2.type options:NSNumericSearch];? Use NSNumericSearch to compare. Commented Mar 29, 2017 at 14:38

1 Answer 1

3

As Larme suggested you need to use Comparator with NSNumericSearch, you can also combined with NSSortDescriptor

NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"type" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
    return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
}];
NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameDescriptor]];
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, works a treat. Thank you
@jampez77 Welcome mate :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.