NSSortDescriptor sort a string field as a number with comparator block not working

core-data, ios

Solution

Try this !

[NSSortDescriptor sortDescriptorWithKey:@"name"
ascending:YES
selector:@selector(localizedStandardCompare:)]

Problem

I have a field full of ids from a third party. The ids are numbers but written to the db as a string. I want to sort a fetch sorted by this id on the value of the integer. So I'm adding this `NSSortDescriptor` to the `NSFetchRequest`. ``` NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init]; [numFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; NSSortDescriptor *sortBy = [[NSSortDescriptor alloc] initWithKey:@"someId" ascending:YES comparator:^(id a, id b) { return [[numFormatter numberFromString:a] compare:[numFormatter numberFromString:b]]; }]; [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortBy]]; ``` But I get results like the the following. These are still sorted as a string, alphabetically. ``` 730275292 73900038 730172867 7350727 830138437 835164 837287901 8338804 930274 9324376 ``` What am I not understanding about using this comparator block? EDIT May 1 2012 9:20 AM EST To test whether the comparator block is being used, I tried the following to sort based on the length of the field. ``` NSSortDescriptor *sortBy = [[NSSortDescriptor alloc] initWithKey:@"fbId" ascending:YES comparator:^(id a, id b) { if ([a length] < [b length]) { return NSOrderedAscending; } else if ([a length] > [b length]) { return NSOrderedDescending; } else { return NSOrderedSame; } }]; [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortBy]]; ``` I'm still getting results sorted by the alphabetically order! So this makes me think the comparator block is not even being used. ``` 716164250 726354466 73900038 739600038 7450727 810138437 801164 801375346 8213997 ```

Original source

Related problems