Working with NSDictionary in Objective-C

The concept of Dictionaries are synonymous with most object-oriented languages, and Objective-C is no exception. Dictionaries via the class NSDictionary allow you to to use words and other sorts of objects as keys, and retrievable via the key of your choosing. For example, to create a dictionary, you do this:

NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys: @"userName", 
    @"DoronK", @"password", @"testPwd", nil]; //end with nil

To access a particular dictionary item, you do the folowing:

NSLog(@"%@", [dic objectForKey@"password");
...

[dic release];  //don't forget to do this

Dictionaries are also enumer-atable, just as you can do with arrays.

NSEnumerator *enumerator = [dic keyEnumerator];
id key;
while ((key = [enumerator nextObject])){
    NSLog(@"%@", [dic objectForKey: key]);
}

Like NSMutableArray, there is an NSMutableDictionary, which allows you to add and remove dictionary items dynamically. It works the same way as you would with any other Mutable object, so read up on the references Apple have provided.
 

Advertisements
This entry was posted in General, iOS and tagged , . Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s