iOS6 Sort JSON objects

2019-09-16 16:38发布

问题:

In my json file I have a title, subtitle, and url.

I sort the title to set the items alphabetically, but the url isn't sorted with the title and I don't know why.

This is what i've done:

NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    NSArray *arrayOfItems = [allDataDictionary objectForKey:@"items"];

    for (NSDictionary *diction in arrayOfItems) {
        NSString *titles = [diction objectForKey:@"title"];
        NSString *station = [diction objectForKey:@"url"];

        [jsonArray addObject:titles];
        [jsonStations addObject:station];

// SORT JSON
        NSArray *sortedArray;
        sortedArray = [jsonArray sortedArrayUsingComparator:^NSComparisonResult(NSString *title1, NSString *title2)
                       {
                           if ([title1 compare:title2] > 0)
                               return NSOrderedDescending;
                           else
                               return NSOrderedAscending;
                       }]; 
        [jsonArray setArray:sortedArray];

What happens is, if I press the first item in the tableView, I get get the url from a total diffrent title. What should I do to get the title to match the url and title in the tableView?

Any help appreciated

EDIT: here's the tableView:didSelectRowAtIndexPath

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if(indexPath.row == _currentRadio) {
        return;
    }

    if(_radio) {
        [_radio shutdown];
        [_radio release];
        _radio = nil;
    }

    [_statusLabel setText:@""];
    [_titleLabel setText:@""];

    _currentRadio = indexPath.row;
    NSString *radioUrl = [jsonStations objectAtIndex:indexPath.row];
    if([radioUrl hasPrefix:@"mms"]) {
        _radio = [[MMSRadio alloc] initWithURL:[NSURL URLWithString:radioUrl]];
    } else {
        _radio = [[HTTPRadio alloc] initWithURL:[NSURL URLWithString:radioUrl]];
    }

    if(_radio) {
        [_radio setDelegate:self];
        [_radio play];
    }



    [self.tableview reloadData];
}

回答1:

The code was placed wrong, another setup for the code, fixed the sorting problem.