How to add to an NSDictionary
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];
By setting you'd use setValue:(id)value forKey:(id)key
method of NSMutableDictionary
object:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:[NSNumber numberWithInt:5] forKey:@"age"];
Or in modern Objective-C:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict[@"age"] = @5;
The difference between mutable and "normal" is, well, mutability. I.e. you can alter the contents of NSMutableDictionary
(and NSMutableArray
) while you can't do that with "normal" NSDictionary
and NSArray