2

I am currently parsing my NSArray through this code

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];
[myArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];

And myArray objects is Ep 1 to Ep 50, unsorted. The problem is in the number with a single digit value. And I cannot add a 0 prefix to it cause the array is dynamic and some object might cause crash.

I am expecting this:

Ep 1 Ep 2 Ep 3..... Ep 10 Ep 11 Ep 12 Ep 13.... Ep 20 Ep 21...

But my output is this

Ep 1 Ep 10 Ep 11 Ep 12 Ep 13..... Ep 2 Ep20 Ep 21 Ep 22.... Ep 3 Ep 30 Ep 31......

Now, How can I sort it properly?

Nirav D
  • 71,513
  • 12
  • 161
  • 183

1 Answers1

3

You need to use NSNumericSearch option with sortedArrayUsingComparator like this.

If your array contains custom object.

NSArray *sortedArray = [myArray sortedArrayUsingComparator:^(Episode *ep1, Episode *ep2) {
     return [ep1.title compare:ep2.title options:NSNumericSearch];
}];

If your array contains NSDictionary.

NSArray *sortedArray = [myArray sortedArrayUsingComparator:^(NSDictionary *dic1, NSDictionary *dic2) {
     return [(NSString*)[dic1 objectForKey:@"title"] compare:(NSString*)[dic2 objectForKey:@"title"] options:NSNumericSearch];
}];
Nirav D
  • 71,513
  • 12
  • 161
  • 183