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 ?
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 ?
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.
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:@"nvjd" forKey:@"name"];
or
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"nvjd",@"name" nil];
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"];