Objective-C - tableView,按降序排序JSON数组

时间:2014-04-22 17:08:35

标签: ios objective-c arrays 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

有关我如何做到的任何提示?

2 个答案:

答案 0 :(得分:0)

如果要对数组进行排序,最好的方法是查看NSArray文档,搜索单词" sort"并选择一个对数组进行排序的方法。 sortedArrayUsingComparator:是我个人的最爱。

答案 1 :(得分:0)

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

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