排序JSON对象

时间:2012-12-26 15:56:25

标签: objective-c json ios5 sorting nsmutablearray

我有3个MutableArray,但只想使用其中一个,在tableView中对它们进行排序。

jsonArray = [[NSMutableArray alloc] init]; //NAME
jsonStations = [[NSMutableArray alloc] init]; //URL
jsonSubtitle = [[NSMutableArray alloc] init]; //TABLEVIEW CELL SUBTITLE

我想使用jsonArray对tableView中的所有json数据进行排序。

下面是我如何得到json数据:

    NSURL *url = [NSURL URLWithString:@"http://www.xxxxx.com/xxx.json"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    connection = [NSURLConnection connectionWithRequest:request delegate:self];
    if(connection)
    {
        jsonData = [[NSMutableData alloc] init];
    }

...

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    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 *subtitles = [diction objectForKey:@"subtitle"];
        NSString *station = [diction objectForKey:@"url"];

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

        [self.tableview reloadData];

    }    
}

Sooo如何按titles排序我的jsonArray并显示然后在tableView中排序?

1 个答案:

答案 0 :(得分:1)

这是你可以对它进行排序的方法:

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