在UserDefaults中使用NSmutableDictionary在NSMutableArray中插入对象

时间:2015-01-31 08:36:14

标签: objective-c nsuserdefaults nsmutabledictionary

我有一个NSMutableArray。该数组存储NSMutableDictionary。字典对象存储NSUserDefault值。这些是用户先前选择的滑块值。现在我想要,当用户移动这些滑块时,必须在NSUserDefaults中保存新的滑块值。

我正在使用此方法在NSMutableArray中添加值

NSMutableArray *quarterValueArray = [[[NSUserDefaults standardUserDefaults]arrayForKey:@"QuarterValues"] mutableCopy];
if (!quarterValueArray)
{
    NSMutableArray *aQuarterArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < 12; i++)
    {
         NSMutableDictionary *dict1 = [[[NSMutableDictionary alloc] init] mutableCopy];
        [dict1 setObject:@"" forKey:@"quarterP"];
        [dict1 setObject:@"" forKey:@"quartersliderValue"];
        [dict1 setObject:@"" forKey:@"totalOfTheQuater"];
        [aQuarterArray addObject:dict1];
    }
    [[NSUserDefaults standardUserDefaults] setObject:aQuarterArray forKey:@"QuarterValues"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

然后用于存储滑块值我在sliderviewCntroller中使用此方法

-(void)saveUserDefaultDataQuarter
{
    NSMutableDictionary *quarter = [QuarterValueArray objectAtIndex:0];
    [quarter setObject:totalQuarter1txt.text forKey:@"totalOfTheQuater"];
    [quarter setObject:showQuartertxt.text forKey:@"quarterP"];
    [quarter setObject:[NSString stringWithFormat:@"%d",(int)slider4.value]forKey:@"quartersliderValue"];
  }


QuarterValueArray =[[[NSUserDefaults standardUserDefaults]arrayForKey:@"QuarterValues"]mutableCopy];

为什么在第二次调用该方法时此代码会崩溃?崩溃日志说:

由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:' - [__ NSCFDictionary setObject:forKey:]:发送到不可变对象的mutating方法'

1 个答案:

答案 0 :(得分:-2)

试试这个。

    NSMutableArray *quarterValueArray = [[[NSUserDefaults standardUserDefaults]arrayForKey:@"QuarterValues"] mutableCopy];
if (!quarterValueArray)
{
    NSMutableArray *aQuarterArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < 12; i++)
    {
        NSMutableDictionary *dict1 = [[[NSMutableDictionary alloc] init] mutableCopy];
        [dict1 setObject:@"" forKey:@"quarterP"];
        [dict1 setObject:@"" forKey:@"quartersliderValue"];
        [dict1 setObject:@"" forKey:@"totalOfTheQuater"];
        [aQuarterArray addObject:dict1];
    }
    [[NSUserDefaults standardUserDefaults] setValue:aQuarterArray forKey:@"QuarterValues"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
[self saveUserDefaultDataQuarter];
NSLog(@"%@",quarterValueArray);

并像这样修改。

-(void)saveUserDefaultDataQuarter{
NSMutableArray*QuarterValueArray =[[[NSUserDefaults standardUserDefaults]arrayForKey:@"QuarterValues"]mutableCopy];
NSMutableDictionary *quarter = [QuarterValueArray objectAtIndex:0];
[quarter setValue:totalQuarter1txt.text forKey:@"totalOfTheQuater"];
[quarter setValue:showQuartertxt.text forKey:@"quarterP"];
[quarter setValue:[NSString stringWithFormat:@"%d",(int)slider4.value]forKey:@"quartersliderValue"];                      }

UPDATE :我已经使用设置值来设置字典键值,因为在我们修改值时已经创建了字典。