iOS – tableView,按降序对JSON数组进行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
进行sorting。
我已经得到的答案,如: sortingNSArray的NSArray对象的最佳方法?
要么 :
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES]; stories=[stories sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]]; recent = [stories copy];
但是当我试图实现它时,根据我目前的代码结构,它并不适用于我。
根据我提供的代码,你能指导我如何解决这个问题吗?
您需要使用您想要sorting的字段的关键path:
-(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]]; }
使用id_no
作为dictionary
key
在这里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
not key
dictionary
not key
的interest
编辑 : descending order
设置ascending:NO