Dictionaries in Objective-C

I was asked to write a blog which documents my journey to discovering Objective-C


… and that’s pretty much how I feel right now.

Heard of a dictionary?


Something like that. I’m talking about an NSDictionary, which stores objects by key-value pairs.

If that isn’t English enough for you, we have a unique key that points to a value, and save that.


First, lets start with creating one. The standard way to alloc / init

NSDictionary *myDict1 = [[NSDictionary alloc] init];

Second, create one with a literal (if you know what values you want inside)

NSDictionary *myDict2 = @{@"british": @"british English", @"american":@"american English"};

Third, my favorite-

NSDictionary *myDict3 = [NSDictionary dictionary];

please note that the first & third dictionaries will be empty!

Next lets see how we can pull things out of our dictionary.

NSString *murica = [myDict2 objectForKey:@"american"];

so our string name ‘murica’ now is equal to @”american English”

For our friends in the United Kingdom,

NSString *uk = myDict2[@"british"];

so the string name ‘uk’ is now equal to @”british English”.

Remember when I mentioned earlier that dictionaries hold objects? They really do!


can you feel the excitement

That means dictionaries can hold other dictionaries. Is your mind blown? Mine is..

lets look at this in detail:

NSDictionary *muppets = @{@"Muppets":@{@"Kermit":@"the frog"}, @{@"Statler":@"the sleepy old dude that complains and hates"}, @{@"Waldorf":@"the mean looking old dude that complains and hates"}, @{@"Fozzie":@"a bear that makes awful jokes"}}

so for our dictionary Muppets, we are holding the keys ‘Kermit’, ‘Statler’, ‘Waldorf’, and ‘Fozzie’, with their respective values.

For accessing the objects within the dictionary, here is a short project

there is more than one way to access the values in the dictionary “theDict”

someMuricanWord = [[theDict objectForKey:@"american"] objectForKey:@"airplane"];
someBritWord = theDict[@"british"][@"behaviour"];

easy like a sunday morning, right?





Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s