Objective-C – NSDictionary Example

NSDictionary is a useful object to store key-pair values just like HashMap in Java.

You can create and iterate a NSDictionary as follow

// Create a NSDictionary
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", @"key3", nil];
NSArray *objs = [NSArray arrayWithObjects:@"obj1", @"obj2", @"obj3", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:objs forKeys:keys];
	
// Iterate it
for (id key in dict) {
	NSLog(@"key: %@   value:%@", key, [dict objectForKey:key]);
}

 

But if you want to take control on the memory management, the following piece of code should be used

// Initialize the required object
NSArray *keys = [[NSArray alloc] initWithObjects:@"key1", @"key2", @"key3", nil];
NSArray *objs = [[NSArray alloc] initWithObjects:@"obj1", @"obj2", @"obj3", nil];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:objs forKeys:keys];
	
// Do not release the arrays here
//[keys release];
//[objs release];
	
// Iterate the NSDictionary
for (id key in dict) {
	NSLog(@"key: %@   value:%@", key, [dict objectForKey:key]);
}
	
// Release after used
[keys release];
[objs release];
[dict release];

 

There is another object called NSMutableDictionary. For all mutable class in Cocoa, it contains extra methods and the created instance could be modified in place.

For more information, please refer to the following references:

Done =)

About these ads

2 thoughts on “Objective-C – NSDictionary Example

  1. Rodrigo Duarte

    Suposses that the value of a key is n integer. How can i get this value and put in a integer value ??????

    Thanks

    Reply

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