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:
- stackoverflow – How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?
- stackoverflow – Ask About NSMutableArray (alloc , arrayWithCapacity)
- NSLog NSDictionary Example code
Done =)
Suposses that the value of a key is n integer. How can i get this value and put in a integer value ??????
Thanks
LikeLike
you can’t use integer in NSDictionary as it only works with object. so you have to use NSNumber instead.
StackOverflow – How can I use an integer value as ‘key’ to set value in NSMutableDictionary?
LikeLike
very useful for junior thanks
LikeLike
you are welcome~ =)
LikeLike