4

Possible Duplicate:
How to add to an NSDictionary

When I do that :

NSDictionary *dic = [NSDictionary dictionary];
[dic setValue:@"nvjd" forKey:@"name"];

my app just crash. I don't understand why. How should I add a string in a dictionary ?

Community
  • 1
  • 1
Alexis
  • 16,629
  • 17
  • 62
  • 107

3 Answers3

14

You need to make your dictionary mutable, otherwise it would not respond to the setValue:forKey: selector:

NSMutableDictionary *dic = [NSMutableDictionary dictionary];

This is a common pattern in cocoa: you often see classes declared in pairs: NSArray/NSMutableArray, NSSet/NSMutableSet, NSString/NSMutableString, and so on. Mutable version is capable of doing everything that the immutable version can do, but it also supports operations that change its content.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
6
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:@"nvjd" forKey:@"name"];    

or

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"nvjd",@"name" nil];
janusfidel
  • 8,036
  • 4
  • 30
  • 53
1

You have two options. Either you initialize your NSDictionary with a key/value pair (or more than one), or create an NSMutableDictionary and add it later.

// Immutable
NSDictionary *dic = [NSDictionary dictionaryWithObject:@"nvjd" forKey:@"name"];

// Mutable
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:@"nvjd" forKey:@"name"];    
Alladinian
  • 34,483
  • 6
  • 89
  • 91