iOS - tableView,按降序排序JSON数组

时间:2014-04-22 18:20:35

标签: ios objective-c json uitableview sorting

这是JSON,按降序显示,id_no

 {"users":[
{"id_no":"501",
 "type":"User",
   "country":"United Kingdom",
   "city":"London"
 }    
 {"id_no":"500",
 "type":"Admin",
   "country":"United States",
   "city":"San Fransisco"}
 ]

这是我的代码:

 - (void)viewDidLoad
{
[super viewDidLoad];
NSURL *jsonURL = [NSURL URLWithString:@"http://example.com/sohw.php"];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.reports = [dataDictionary objectForKey:@"users"];
}

我想要做的是按照JSON文件在tableView上显示时按降序排序users

我已经得到了如下答案: Best way to sort an NSArray of NSDictionary objects?

或:

  NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest"  ascending:YES];
   stories=[stories sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
   recent = [stories copy];

但是当我尝试实现它时,根据我目前的代码结构,它对我不起作用。

根据我提供的代码,您能指导我如何解决它吗?

2 个答案:

答案 0 :(得分:3)

您需要使用要排序的字段的键路径:

-(void)viewDidLoad
{
    [super viewDidLoad];
    NSURL *jsonURL = [NSURL URLWithString:@"http://example.com/sohw.php"];
    NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
    NSError *error = nil;
    NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

    NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:@"id_no" ascending:NO];
    self.reports = [[dataDictionary objectForKey:@"users"] sortedArrayUsingDescriptors:@[sorter]];
}

答案 1 :(得分:2)

id_no用作keydictionary这里的sort

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"id_no"  ascending:NO];
NSArray *users=[self.reports sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];

self.reports = [users mutableCopy];

Mistake您完成的是used interest not key dictionary

编辑:对于descending order设置ascending:NO