How to Use Objective-C Dictionaries

How to Use Dictionaries

Like an array, a dictionary is a list of objects. However, dictionaries make it
easier to organize data by providing “keys” that make it a snap to find the
things you put in there. These are sometimes referred to as a hash or a
hash-table.

Instantiate a dictionary

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; 



Add objects to a dictionary indexed by keys

[dictionary setObject:@"A Book about the Letter A" forKey:@"A"];
[dictionary setObject:@"A Book about the Letter B" forKey:@"B"];
[dictionary setObject:@"A Book about the Letter C" forKey:@"C"];

Retrieve an object from a dictionary with a key

NSLog([dictionary objectForKey:@"B"]);



Release a dictionary

[dictionary release];



Cool – hope you enjoyed this snippet of da codes! Once you get use to the square brackets and verbose parameter prefixes Objective-C starts to feel like the programming languages that you are used to.

3 Responses to How to Use Objective-C Dictionaries

  1. iPhoneKicks.com July 6, 2009 at 12:21 pm #

    How to Use Objective-C Dictionaries…

    You’ve been kicked (a good thing) – Trackback from iPhoneKicks.com – iPhone SDK links, community driven…

  2. roostert July 14, 2009 at 7:20 pm #

    This is a nice introductory.

    How about some examples on using Arrays in Dictionaries and how to use them in Table Views?

    What is the fastest way to access them, etc.

  3. mattjdrake July 15, 2009 at 11:18 am #

    Using an array is a dictionary is actually the same as using a string in a dictionary. You just stick in an array instead of a string in the setObject message. Here is an example:

    //create dictionary
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

    //create an array and put something (anything) into the array
    NSMutableArray *stuffInList = [[NSMutableArray alloc] init];
    [stuffInList addObject:@"Something in a list"];

    //put the array into the dictionary
    [dictionary setObject:stuffInList forKey:@"Object001"];

    //as an example retrieve the array from the dictionary
    NSArray *NSTempArray = [dictionary objectForKey:@"Object001"];

    //write out the first object in the array to the log
    NSLog([NSTempArray objectAtIndex:0]);

    As far as using structures like this in a table view. It sort of depends on how you design your data model and that is a big topic that will vary over developers, app and developer+app combinations. However you decided to do it the table view controller delegate methods of interested are:

    numberOfSectionsInTableView

    numberOfRowsInSection

    cellForRowAtIndexPath

    These delegate methods all do what they sound like… Hope that helps!

Leave a Reply

Switch to our mobile site