user440096
user440096

Reputation:

Moving through a NSDictionary getting objects that you do not know the 'Key' for? IOS

I have a NSDictionary that I get from a webservice. Each object in this dictionary contains an array. I do not know how many objects there are going to be in the NSDictionary, or what the 'Key' for each object is going to be beforehand. I only know that it will be a Dictionary of arrays.

How can I enumerate through the dictionary reading out the name of the Object and its content into arrays?

All my dealings with Dictionaries so far I could use

[anotherDict objectForKey:@"accounts"]

because I know the 'Keys; to expect beforehand.

Many Thanks, -Code

Upvotes: 1

Views: 847

Answers (5)

Damien Locque
Damien Locque

Reputation: 1809

you can do this :

NSArray * keys = [dictionnary allKeys];
for (NSString *key in keys) {
   NSArray *tmp = [dictionnary objectForKey:key];
}

Upvotes: 0

atastrophic
atastrophic

Reputation: 3143

Simplest Way WOuld be to fetch allKeys via the allKeys instance method

NSArray *keys = [myDictionary allKeys];

then iterating over dictionary with for each key.

for (NSString *k in keys)
{
    id object = [myDictionary objectForKey:k];
}

You can also get keys in order as if values were sorted using

NSArray *sortedKeys = [myDictionary keysSortedByValueUsingSelector:@selector(compare:)];

Upvotes: 1

Jonathan Naguin
Jonathan Naguin

Reputation: 14796

NSDictionary has the method: enumerateKeysAndObjectsUsingBlock: since iOS 4.0. It's very straightforward, it receives a block object to operate on entries in the dictionary.

An example:

[anotherDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
   NSArray *arr = obj;
   //Do something
}

Upvotes: 5

graver
graver

Reputation: 15213

NSDictionary class has an instance method -allKeys which returns an NSArray with NSStrings for all the keys.

Upvotes: 1

superGokuN
superGokuN

Reputation: 1424

i am not a pro but i know that you can get all the keys of an dictionary

 NSLog(@"%@",[Your_Dictionary allKeys]);

This will give an array of keys in that dictionary.

Upvotes: 0

Related Questions