Sponsored By

How to work with NSDictionary in Objective-C ?

This tutorial will address few issues. 1. How to create dictionary by using Array. 2. Add records to dictionary by using KVC. 3. Retrieving value from NSDictionary.

willie shi

February 24, 2014

2 Min Read

This tutorial will address few issues.
1. How to create dictionary by using Array.
2. Add records to dictionary by using KVC.
3. Retrieving value from NSDictionary.

Using method bellow to create dictionary.

-(void)createDict{

// ### creating Key array
NSArray *models = @[@"Mercedes-Benz", @"Ford",
@"GM", @"chrysler"];

// ### creating Value array
NSArray *stock = @[[NSNumber numberWithInt:10],
[NSNumber numberWithInt:20],
[NSNumber numberWithInt:30],
[NSNumber numberWithInt:40]];
// ### creating a dictionary base on array
NSDictionary *inventory = [NSDictionary dictionaryWithObjects:stock forKeys:models];
// ### creating a mutableDictionary in order to deploy key value coding (KVC)
NSMutableDictionary *mDict = [inventory mutableCopy];
// ### add record to existing dictionary
[mDict setValue:[NSNumber numberWithInt:100] forKey:@"Honda"];
// ### add NSString as a value to existing dictionary
[mDict setValue:@"123 in stock" forKey:@"Toyata"];

// ### print out original dictionary
NSLog(@"%@", inventory);
// #### output =>
/*
Ford = 20;
GM = 30;
"Mercedes-Benz" = 10;
chrysler = 40;
*/

// ### print out the Value for Key "chrysler" stored in dictionay
NSLog(@"chrysler has %@ in stock", inventory[@"chrysler"]);
// #### output => chrysler has 40 in stock

// ### print out the Value for Key "Ford" stored in dictionay
NSLog(@"Ford has %@ in stock", [inventory objectForKey:@"Ford"]);
// #### output => Ford has 20 in stock

// ### print out all Value from exsiting dictionary
NSLog(@"all value %@", [inventory allValues]);
// #### output => 20, 30, 40, 10

// ### print out formatted all Value from exsiting dictionary
for (NSString *str in [inventory allValues]) {
NSLog(@"All value: %@", str);
// #### output =>
/*
All value: 20
All value: 30
All value: 40
All value: 10
*/
}

// ### print out formatted all Value from mutableDictionary
for (NSString *str in [mDict allValues]) {
NSLog(@"mDict value: %@", str);
// ### output = >
/*
mDict value: 20
mDict value: 30
mDict value: 40
mDict value: 10
mDict value: 100
mDict value: 123 in stock
*/
}

// ### storing the value for Key "Toyata" in NSString
NSString *dValue = [mDict valueForKey:@"Toyata"];

// ### retrieving the doubleValue for Key "Toyata" stored in mutableDictionary
// ### cut the string "in stock", only pront out the number in double format.
NSLog(@"dValue: %.2f", [dValue doubleValue]);
// ### output = > dValue: 123.00
}

Read more about:

Blogs

About the Author(s)

Daily news, dev blogs, and stories from Game Developer straight to your inbox

You May Also Like