1

嗨,我知道在我想知道我的代码哪里出错之前会问这个问题。所以我问这个问题..我正在尝试将 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]];
      }
}
4

1 回答 1

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];
于 2013-01-22T11:12:00.037 回答