Reputation: 283
I have an app that receives an Json file from my webserver and I convert to NSDictionary as you can see below:
[NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError]
The structure of my dictionary is as follows:
[0] => { "name" = "josh", meters = "8" }
[1] => { "name" = "lina", meters = "10" }
[2] => { "name" = "pall", meters = "21" }
You can see that data is already organized by the key meters
, unfortunately my webserver not give the possibility to maintain an open connection, in this case, the new records will come through the APNS (push notification)
Assuming that comes the following record by notification:
{"name" = "oli", meters = "12"}
I insert it in my dictionary, but once that's done, how can I rearrange my array and order by meters?
Upvotes: 0
Views: 51
Reputation: 62686
There's no order inherent in the dictionary. That you see an ordering in the initial set is accidental.
Arrays have ordering, and you can get an array from a dictionary by sending it allKeys
or allValues
.
Using this fact to organize the dictionary, you might try something like this:
NSArray *orderedPairs = [@[] mutableCopy];
for (id key in [someDictionary allKeys]) {
[orderedPairs addObject:@[key, someDictionary[key]]];
}
[orderedPairs sortUsingComparator:^NSComparisonResult(NSArray *a, NSArray *b) {
// return [a[0] compare:b[0]]; // to sort by key
return [a[1] compare:b[1]]; // to sort by value
}];
Note that this will result in an array -- not a dictionary -- but one that is ordered.
Upvotes: 2
Reputation: 27428
Dictionary doesn't have order. it's simply key-value pair. you can fetch value for particular key so doesn't require sorting or ordering like array.
Upvotes: 0