Reputation: 1364
From API, I am able to get below format.
{
"status": true,
"data": {
"29": "Hardik sheth",
"30": "Kavit Gosvami"
}
}
In that, I want to fetch Key and value both.
How can I do this using NSDictionary?
Upvotes: -1
Views: 60
Reputation: 131481
Are you using Swift or Objective-C?
In Objective-C you'd use allKeys to get the list of keys, as outlined by @BhavinSolanki in his answer.
In Swift you could do that as well (using the Swift
Dictionary
keys
property, myDictinoary.keys
)
Alternately you could use tuples to loop through the keys and values:
for (key, value) in dictionary {
NSLog (@"Key: %@ for value: %@", key, value);
}
Upvotes: 0
Reputation: 1364
Sometime, you need to iterate over all the key/value pairs in a dictionary. To do this, you use the method -allKeys to retrieve an array of all the keys in the dictionary; this array contains all the keys, in no particular (ie random) order. You can then cycle over this array, and for each key retrieve its value. The following example prints out all the key-values in a dictionary:
void
describeDictionary (NSDictionary *dict)
{
NSArray *keys;
int i, count;
id key, value;
keys = [dict allKeys];
count = [keys count];
for (i = 0; i < count; i++)
{
key = [keys objectAtIndex: i];
value = [dict objectForKey: key];
NSLog (@"Key: %@ for value: %@", key, value);
}
}
As usual, this code is just an example of how to enumerate all the entries in a dictionary; in real life, to get a description of a NSDictionary, you just do NSLog (@"%@", myDictionary);
.
Upvotes: 0