user3405229
user3405229

Reputation: 85

iOS - tableView, sort JSON array in descending order

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

This is my code :

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

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

I have already got answers such as : Best way to sort an NSArray of NSDictionary objects?

or :

  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 ?

Upvotes: 1

Views: 2152

Answers (2)

Paresh Navadiya
Paresh Navadiya

Reputation: 38239

Use id_no as key which is in dictionary to sort here

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

self.reports = [users mutableCopy];

Mistake you done is used interest which is not key of dictionary

EDIT : for descending order set ascending:NO

Upvotes: 2

Rich
Rich

Reputation: 8202

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

Upvotes: 3

Related Questions