How to store multiple NSMutableDictionarys in NSUserDefaults

39 views Asked by At

I am trying to store multiple NSMutableDictionarys in NSUserDefaults I have tried this:

-(void)storeNotification:(NSDictionary*)dict{
    NSMutableDictionary *dic = [dict mutableCopy];
    //add read object to dic
    [dic setObject:@"NO" forKey:@"read"];

    //get stored arrayofdics
    NSMutableArray *arrayofdics = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayofdics"];
    if([arrayofdics count] == 0){
        arrayofdics = [[NSMutableArray alloc] init];
    }

    //add dic to arrayofdics
    [arrayofdics addObject:dic];

    //store arrayofdics
    [[NSUserDefaults standardUserDefaults] setObject:arrayofdics forKey:@"arrayofdics"];
    NSLog(@"stored: %@", arrayofdics);
}

So that I can then modify the read key in a dic like this:

-(void)markAsRead:(int)dic_index{
    NSMutableArray *arrayofdics = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayofdics"];
    NSMutableDictionary *dic = [arrayofdics objectAtIndex:dic_index];
    [dic setObject:@"YES" forKey:@"read"];
    [arrayofdics replaceObjectAtIndex:dic_index withObject:dic];
    [[NSUserDefaults standardUserDefaults] setObject:arrayofdics forKey:@"arrayofdics"];
}

and also am able to iterate all of the storeNotifications


The log is showing:

stored: ( { read = NO; ... })

but when storeNotification is called the second time I get an error:

Printing description of arrayofdics->isa:
(Class) isa = __NSCFArray
(lldb) 

enter image description here

Which means the array is not being stored properly. Any ideas why? Or ways to do this better?

1

There are 1 answers

0
iTamilan On BEST ANSWER

This error is due to calling mutable functions in immutable objects

Userdefaults always return a immutable objects. so make mutable when u get objects from userdefaults.

 NSMutableArray *arrayofdics = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayofdics"] mutableCopy];