sortedArrayUsingComparator int

时间:2011-06-03 13:27:33

标签: objective-c xcode

我有一个字典数组,sortArrayUsingComparator根据键对它们进行排序;

listPerc = [listItem sortedArrayUsingComparator: ^(id a, id b) {
    NSString *first = [a objectForKey:@"perc"];
    NSString *second = [b objectForKey:@"perc"];
    return [first compare:second];
问题是这个键是一个数字,例如:1,10,15,17,2,23等。 它不计算数字的大小。 我怎么办?

4 个答案:

答案 0 :(得分:18)

你不能像这样返回比较结果,

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;
    }
}

答案 1 :(得分:7)

@(Deepak Danduprolu)答案的简短方法

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

}

答案 2 :(得分:4)

将它们转换为NSNumber对象并进行比较。要么将它们存储为NSNumbers(首选方法),要么在比较时转换它们(较慢)。

将NSString转换为NSNumber可以通过以下方式完成:

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

答案 3 :(得分:0)

也许你可以做这样的事情。

- (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];
    }
}

我做了一些你和你之间的交叉,它起作用了:

- (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