开发者

sortedArrayUsingComparator int

I have an array of a dictionary that it sortedArrayUsingComparator sorts them based on the key;

listPerc = [listItem sortedArrayUsingComparator: ^(id a, id b) {
    NSString *first = [a objectForKey:@"perc"];
    NSStr开发者_开发知识库ing *second = [b objectForKey:@"perc"];
    return [first compare:second];

the problem is that this key is a numbers, and order is so for example: 1,10, 15, 17, 2, 23, etc. it does not calculate the magnitude of the number. how can I do?


Can't you return the comparison result like this,

listPerc = [listItem sortedArrayUsingComparator: ^(id a, id b) {
    int first = [[a objectForKey:@"perc"] intValue];
    int second = [[b objectForKey:@"perc"] intValue];

    if ( first < second ) {
        return (NSComparisonResult)NSOrderedAscending;
    } else if ( first > second ) {
        return (NSComparisonResult)NSOrderedDescending;
    } else {
        return (NSComparisonResult)NSOrderedSame;
    }
}


A very short way of @(Deepak Danduprolu)'s answer

listPerc = [listItem sortedArrayUsingComparator: ^(id a, id b) {
    NSNumber *first = @([[a objectForKey:@"perc"] intValue]);
    NSNumber *second = @([[b objectForKey:@"perc"] intValue]);
    return [first compare:second];
}


Make them into NSNumber objects and compare those instead. Either store them as NSNumbers to start with (preferred method) or convert them when comparing (slower).

Converting an NSString to an NSNumber can be done with:

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:string];
[f release];


Maybe you can do something like this.

- (void)setPlaces:(NSArray *)places
{
    if(_places != places)
    {
        _places = [places sortedArrayUsingComparator:^(id obj1, id obj2){
            return [[obj1 objectForKey:FLICKR_PLACE_NAME] caseInsensitiveCompare:[obj2 objectForKey:FLICKR_PLACE_NAME]];
        }];
        [self.tableView reloadData];
    }
}

I did something that was a cross between yours and the above and it works:

- (void)setPlaces:(NSArray *)places
{
    if(_places != places)
    {
        _places = [places sortedArrayUsingComparator:^(id a, id b){
              NSString *first = [a objectForKey:FLICKR_PLACE_NAME];
              NSString *second = [b objectForKey:FLICKR_PLACE_NAME];
              return [first caseInsensitiveCompare:second];
        }
            ];
        if (self.tableView.window) [self.tableView reloadData];
    } //if _places
} //set
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜