I am trying to store multiple NSMutableDictionary
s 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 storeNotification
s
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)
Which means the array is not being stored properly. Any ideas why? Or ways to do this better?
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.