Search code examples
sortingfor-loopios6nsjsonserialization

Sorting NSJSON arrays aren't working properly


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

When 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 in the tableView?


Solution

  • First of all this seems like a strange way of sorting, you should use a dictionary instead of 2 arrays otherwise things get messy very quickly.

    Secondly you need to pass your sortedArray to the table instead of the jsonArray currently it seems to be just trying to reset the jsonArray.

    I would create one method to handle it like this (I have stripped some of your sorting script to simplify this)

    -(NSArray *)sortContentWithJSONData {
        NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        NSArray *arrayOfItems = [allDataDictionary objectForKey:@"items"];
        NSArray *sortedArray = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:false];
        NSMutableArray *outputArray = [[NSMutableArray alloc] init];;
        for (NSDictionary *diction in arrayOfItems) {
            NSString *titles = [diction objectForKey:@"title"];
            NSString *station = [diction objectForKey:@"url"];
    
            [outputArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:titles, @"title", station, @"station", nil]]
    
        }
    
        return [outputArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortedArray]];
    
    }
    

    Then you could set a global array and access it in your table view using the following...

    NSArray *tableContent = [self sortContentWithJSONData];
    

    Hope that clears things up a bit :)