Helium3 Helium3 - 5 months ago 17
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?

Regards.

Answer

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