Retrieving data from a NSDictionary

system picture system · Jul 8, 2010 · Viewed 14.1k times · Source

I am not quite sure I understand how to do the following.

If I wanted to add e.g. an author and a title (key, value) to a dictionary. Fill that dictionary with data, then have another dictionary for say e.g. k = genre v = artist name and fill it with data.

Then I want to add the dictionaries to an array.

Firstly how is that done? and secondly, what if I allow the user to log their own entries. So I have to textfields on screen, when the user is done, it stores the fields as key value pair in a new dictionary e.g. user's dictionary.

What will I do later when trying to fill a tableview with the users entered data, I dont know the keys or values in that dictionary so how could I retrieve that data?

I mean let's say I want to load the user's dictionary from array index 2 and fill a tableview's cells with each dictionary entry, how is this done? Maybe a method like on an array(get entry.title at index blah blah ), get Key value in dictionary?

How else can one actually get loaded user entered data that they arent aware of the values?

Regards

Answer

Carl Norum picture Carl Norum · Jul 8, 2010

Add author and title to a dictionary (assuming they're objects that already exist - likely NSString instances in your case):

NSMutableDictionary *books = [[NSMutableDictionary alloc] initWithCapacity:10];
[books setObject:title forKey:author];

Same thing for genre/artist:

NSMutableDictionary *music = [[NSMutableDictionary alloc] initWithCapacity:10];
[books setObject:artist forKey:genre];

Then put them in an array:

NSArray *theArray = [NSArray arrayWithObjects:books, music, nil];

Then to read out the stuff at array index 2:

id key;
NSDictionary *theDictionary = [theArray objectAtIndex:2];
id value;
for (key in [theDictionary allKeys])
{
    value = [theDictionary objectForKey:key];
    // do something with the value
}