How to add to an NSDictionary

system picture system · Jul 1, 2010 · Viewed 170.2k times · Source

I was using a NSMutableArray and realized that using a dictionary is a lot simpler for what I am trying to achieve.

I want to save a key as a NSString and a value as an int in the dictionary. How is this done? Secondly, what is the difference between mutable and a normal dictionary?

Answer

Eiko picture Eiko · Jul 1, 2010

A mutable dictionary can be changed, i.e. you can add and remove objects. An immutable is fixed once it is created.

create and add:

NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
[dict setObject:[NSNumber numberWithInt:42] forKey:@"A cool number"];

and retrieve:

int myNumber = [[dict objectForKey:@"A cool number"] intValue];