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"];
    NSString *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?


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

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


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

Need Your Help

JavaFx 2 create TableView with single column

java layout tableview javafx-2

I am trying to create a table with a single column using the following code :

XmlHttp Request Basic Authentication Issue

authentication asp-classic xmlhttprequest

I have the following code that creates a serverside object of the xmlhttp class. I am trying to connect to a site that requires basic authentication. I am able to get this to work with the code b...