Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting NSString values as if NSInteger using NSSortDescriptor

I have created a sort descriptor to sort a plist response coming from my server. This works well with sort key having values upto 9. With more than 10 items I see abrupt results with sort key arranged in the order = 1, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9

NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sort" ascending:YES]; self.myList = [NSMutableArray arrayWithArray:[unsortedList sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]]; 

How to make it arrange in the correct order of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11?

like image 231
Abhinav Avatar asked Mar 12 '12 20:03

Abhinav


2 Answers

You can do this by implementing a custom comparator block when creating your NSSortDescriptor:

NSSortDescriptor *aSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"sort" ascending:YES comparator:^(id obj1, id obj2) {      if ([obj1 integerValue] > [obj2 integerValue]) {         return (NSComparisonResult)NSOrderedDescending;     }     if ([obj1 integerValue] < [obj2 integerValue]) {         return (NSComparisonResult)NSOrderedAscending;     }     return (NSComparisonResult)NSOrderedSame; }]; self.myList = [NSMutableArray arrayWithArray:[unsortedList sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]]; 

See Apple documentation here

like image 101
jonkroll Avatar answered Sep 20 '22 17:09

jonkroll


[list sortUsingSelector:@selector(localizedStandardCompare:)]; will sort the list in a "human" way (so "11" will come last, not between "1" and "2"). But if you really do want to treat these strings as numbers, you should make them number first!

like image 21
Vincent Gable Avatar answered Sep 21 '22 17:09

Vincent Gable