Curnelious
Curnelious

Reputation: 1

NSDictionary is not setting a value

I am getting a nil value for dictionary. I am sure there is something stupid here that i can't find. The user default at the first time is nil, maybe this is the thing ?

 NSDate *date=[NSDate date];
     //read
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] init];
    dic=[[NSUserDefaults standardUserDefaults] objectForKey:@"list"];
    [dic setObject:dataToSave forKey:date];
    NSLog(@"%@",dic);//show nil where "dataToSave" is not nil.

Upvotes: 0

Views: 61

Answers (1)

Dima
Dima

Reputation: 23624

You are initializing the dic var with a new dictionary and then right afterwards re-initializing it with the NSUserDefaults entry, which I guess is nil.

NSDate *date=[NSDate date];
//read
NSMutableDictionary *dic = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"list"].mutableCopy;
if(!dic)
{
    dic = [[NSMutableDictionary alloc] init];
}
[dic setObject:dataToSave forKey:date];

// if you want to save back to NSUserDefaults, you will need to do this
[[NSUserDefaults standardUserDefaults] setObject:dic forKey:@"list"];

Edit

As rmaddy pointed out, this won't work because you cannot use non-NSStrings as keys in dictionaries you save to NSUserDefaults.

In order for this to work, the date var needs to be replaced with a string.

Edit2

modified answer to allow for NSMutableDictionary

Upvotes: 1

Related Questions