Helium3 Helium3 - 7 months ago 31
Objective-C Question

How to add to an NSDictionary

I was using a NSMutableArray and realised 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. firstly , how is this done? Secondly, what is the difference between mutable and a normal dictionary?



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];