How to Use Objective-C Dictionaries

by mattjdrake on July 1, 2009

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.

Please share this if you like it!
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • email
  • FriendFeed
  • LinkedIn
  • MySpace
  • Ping.fm
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Technorati
  • Tumblr
  • Yahoo! Bookmarks

{ 1 trackback }

iPhoneKicks.com
July 6, 2009 at 8:21 am

{ 2 comments }

1 roostertNo Gravatar July 14, 2009 at 3: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.

2 mattjdrakeNo Gravatar July 15, 2009 at 7: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!

Comments on this entry are closed.

Previous post:

Next post: