iOS-tableView,按降序对JSON数组排序 [英] iOS - tableView, sort JSON array in descending order

查看:313
本文介绍了iOS-tableView,按降序对JSON数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是JSON,以降序显示id_no

This is the JSON, it shows by descending order, 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"];
}

我想要做的是当users在tableView上显示时,按照降序对JSON文件进行排序.

What I want to do is to sort users in descending order when displayed on the tableView as per as the JSON file.

我已经得到了诸如以下的答案: 对NSDictionary对象的NSArray进行排序的最佳方法?

I have already got answers such as : 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];

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

but when I tried to implement it, it does not worked for me according to my current structure of code.

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

Can you please guide me on how I can solve it, according to the code I provided ?

推荐答案

您需要使用要作为排序依据的字段的键路径:

You need to use the key path of the field you want to sort by:

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

这篇关于iOS-tableView,按降序对JSON数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆