Jump to content

How to work with NSDictionary in Objective-C

+ 1
  Doron Katz's Photo
Posted Nov 27 2010 09:14 PM

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]; //nil to signify end of objects and keys.



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.

Tags:
1 Subscribe


1 Reply

0
  ocoder's Photo
Posted Sep 10 2012 08:44 AM

There are two mistakes in the example code.

1) initWithObjectsAndKeys accepts parameters in the order of @"value", @"key" not @"key", @"value" (despite the fact it seems counterintuitive)

2) The line NSLog(@"%@", [dic objectForKey@"password"); is missing both a colon and closing square bracket.

Hence the code should be written as:

NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:
@"DoronK", @"userName", @"testPwd",
@"password", nil]; //nil to signify end of objects and keys.

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

Also note that the [dic release]; line should not be used with the iOS 5 SDK or higher (that uses ARC).