嗨我知道在我想知道我的代码在哪里出错之前会问这个问题。所以我问这个问题..我试图将nsmutabledictionary的值存储到nsuserdefaults ..
我在uitableviewcell中添加了uiswitch。因此,每次我打开uiswitch它应该存储在nsuserdefaults中,这样当我退出应用程序并重新打开应用程序时,应该打开最后一次打开的开关
- (void)viewDidLoad
{
[super viewDidLoad];
activeNotificationDictionary = [[NSMutableDictionary alloc]init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:@"theKey"];
NSMutableDictionary *artworkDict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
artworkDict = activeNotificationDictionary;
}
-(void)notificationChangedForSymptom:(int)symptomIDNo withRemedyID:(int)remedyID isSelected:(BOOL)isSelected
{
if (isSelected == YES)
{
selectedSymptomID = symptomIDNo;
selectedRemedyID = remedyID;
if ([activeNotificationDictionary objectForKey:[NSNumber numberWithInt:symptomIDNo]] != nil)
{
UIAlertView *selectedNotification = [[UIAlertView alloc]initWithTitle:@"Reminder" message:@"Would you like to change the notification" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
selectedNotification.delegate = self;
NSLog(@" selected remedyID for symptom %@", activeNotificationDictionary);
[selectedNotification show];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *dict = [NSDictionary dictionaryWithObject:activeNotificationDictionary forKey:@"dictKey"];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dict];
[defaults setObject:data forKey:@"theKey"];
[defaults synchronize];
NSLog(@"default value %@",defaults);
}
else
{
[activeNotificationDictionary setObject:[NSNumber numberWithInt:RemedyID] forKey:[NSNumber numberWithInt:SymptomIDNo]];
}
}
else
{
[activeNotificationDictionary removeObjectForKey:[NSNumber numberWithInt:symptomIDNo]];
}
}
答案 0 :(得分:1)
当您对可变字典进行编码时,只会对不可变字典进行编码,因为NSMutableDictionary
不会覆盖NSSecureCoding
方法。所以制作一个可变的副本:
NSData *data = [defaults objectForKey:@"theKey"];
NSMutableDictionary *artworkDict = [[NSKeyedUnarchiver unarchiveObjectWithData:data]mutableCopy];
编辑
我建议在应用启动之前初始化每个默认,例如:
+ (void) initialize // Inside the class storing the defaults
{
NSUserDefaults* defaults= [NSUserDefaults standardUserDefaults];
[defaults registerDefaults: @{ @"theKey":@{} } ];
}
如果要将所有默认值与数据库同步,请调用synchronize:
[defaults synchronize];