问题
I am using a REST based web service to get data. No matter what the structure of the JSON document, the NSDictionary gets populated the same way. I want the sorting preserved as the web service returns.
Here is my code:
-(void) getData
{
NSURL *url = [NSURL URLWithString:@"http://somewebservice"];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
// Use when fetching text data
NSString *responseString = [request responseString];
NSDictionary *resultsDictionary = [responseString objectFromJSONString];
[jokesArray release];
jokesArray = [resultsDictionary allValues]; //always has the same order.
[jokesArray retain];
[self.tableView reloadData];
// Use when fetching binary data
// NSData *responseData = [request responseData];
}];
[request setFailedBlock:^{
NSError *error = [request error];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"An error occured"
message:[error description]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}];
[request startAsynchronous];
}
回答1:
The entries in an NSDictionary
have no inherent order; they are unsorted by definition. The same is true for the array returned by allValues
, as the documentation clearly says:
The order of the values in the array isn’t defined.
You will need to sort the array afterwards. If you want to keep the same sort order that is in the JSON source, you would have to parse the JSON data manually and retrieve the values from the dictionary one after another. Or, if you know how the JSON data is sorted, just apply the same sorting algorithm to the array returned by allValues
.
回答2:
You shouldn't be using JSON dictionary to store things whose order matters. As http://json.org/ says
An object is an unordered set of name/value pairs.
来源:https://stackoverflow.com/questions/7947234/jsonkit-sorting-issues