Objective-C-tableView,按降序对JSON数组进行排序 [英] Objective-C - tableView, sort JSON array in descending order

查看:84
本文介绍了Objective-C-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.

关于我该怎么做的任何提示?

Any hints on how I can do it ?

推荐答案

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

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

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

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