如何在 NSUserDefaults 中存储多个 NSMutableDictionary
How to store multiple NSMutableDictionarys in NSUserDefaults
我正在尝试在 NSUserDefaults
中存储多个 NSMutableDictionary
我试过这个:
-(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);
}
这样我就可以像这样修改 dic 中的 read
键:
-(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"];
}
并且还能够迭代所有 storeNotification
s
日志显示:
已存储:(
{
阅读=否;
...
})
但是当第二次调用storeNotification
时我得到一个错误:
Printing description of arrayofdics->isa:
(Class) isa = __NSCFArray
(lldb)
这意味着数组没有正确存储。任何想法为什么?或者如何更好地做到这一点?
此错误是由于在不可变对象中调用可变函数造成的
Userdefaults 总是 return 不可变对象。
因此,当您从 userdefaults 获取对象时,请使其可变。
NSMutableArray *arrayofdics = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayofdics"] mutableCopy];
我正在尝试在 NSUserDefaults
中存储多个 NSMutableDictionary
我试过这个:
-(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);
}
这样我就可以像这样修改 dic 中的 read
键:
-(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"];
}
并且还能够迭代所有 storeNotification
s
日志显示:
已存储:( { 阅读=否; ... })
但是当第二次调用storeNotification
时我得到一个错误:
Printing description of arrayofdics->isa:
(Class) isa = __NSCFArray
(lldb)
这意味着数组没有正确存储。任何想法为什么?或者如何更好地做到这一点?
此错误是由于在不可变对象中调用可变函数造成的
Userdefaults 总是 return 不可变对象。 因此,当您从 userdefaults 获取对象时,请使其可变。
NSMutableArray *arrayofdics = [[[NSUserDefaults standardUserDefaults] objectForKey:@"arrayofdics"] mutableCopy];