Sorting NSString values as if NSInteger using NSSortDescriptor

Solution 1:

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

Solution 2:

[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!