NSSortDescriptor sorts the string field as a number with a broken comparator block

I have a field full of third party identifiers. IDs are numbers, but are written to db as a string.

I want to sort a selection sorted by this identifier by integer value. So I add this NSSortDescriptorto 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 similar to the following. They are still sorted as a string, in alphabetical order.

730275292
73900038
730172867
7350727
830138437
835164
837287901
8338804
930274
9324376

What I don’t understand about using this comparator block?

EDIT May 1, 2012 9:20 AM EST

To check if the comparator block is used, I tried the following to sort by field length.

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 am still getting results sorted alphabetically! Therefore, it makes me think that the comparator block is not even used.

716164250
726354466
73900038
739600038
7450727
810138437
801164
801375346
8213997
+5
2

!

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

NSFetchRequest, , , , - . , , . , , , :

    NSArray *array = [NSArray arrayWithObjects:@"730275292",
                      @"73900038",
                      @"730172867",
                      @"7350727",
                      @"830138437",
                      @"835164",
                      @"837287901",
                      @"8338804",
                      @"930274",
                      @"9324376", nil];
    NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
    [numFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSArray *sArray = [array sortedArrayUsingComparator:^(id a, id b) {
        return [[numFormatter numberFromString:a] compare:[numFormatter numberFromString:b]];
    }];
    NSLog(@"%@",sArray);

, :

(
    835164,
    930274,
    7350727,
    8338804,
    9324376,
    73900038,
    730172867,
    730275292,
    830138437,
    837287901
)

, , . , . , . , .

, NSFetchRequest , - , . , , .

NSFetchRequest, , , . , resultType :

setResultType: - , . "NSFetchRequestResultType." NSManagedObjectIDResultType, " " , .

, , .

+1
source

All Articles