编辑使用NSUserDefaults保存的NSMutableArray中的对象

时间:2014-03-18 12:10:48

标签: ios objective-c nsmutablearray nsmutabledictionary

当我尝试编辑从[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object获取的对象时,我收到NSUserDefault

我已经搜索了stackoverflow并尝试在检索数据后制作可变副本,但仍然收到错误。这是当前的代码

我在第一个视图控制器中设置了它

        NSMutableArray *settings=[[NSMutableArray alloc]init];

        [settings addObject:[@{
                               @"single":@"Player1",
                               @"multiplesame":[[NSMutableArray alloc] initWithObjects:@"Player1",@"Player2",@"Player3",@"Player4",@"Player5", nil],
                               @"multipleDiff":[UIDevice currentDevice].name

                              }mutableCopy]];   

       [Reusables storeArrayToDefaults:SETTINGS_DETAILS objectToAdd:settings];

现在在另一个视图控制器中,我正在尝试将单个键的Player1的值更改为名称。为此,这就是我检索数据的方式。

NSMutableArray *setDetails = [[[NSUserDefaults standardUserDefaults] arrayForKey:SETTINGS_DETAILS] mutableCopy];

//setDetails= [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:SETTINGS_DETAILS]] ;
//setDetails = [setDetails mutableCopy];

 NSLog(@"Details:%@",setDetails);

日志打印正常

Details:(
        {
        multipleDiff = "iPhone Simulator";
        multiplesame =         (
            Player1,
            Player2,
            Player3,
            Player4,
            Player5
        );
        single = Player1;
    }
)

但是现在当我尝试更改这样的值时,它会因上述错误而崩溃

 [[setDetails objectAtIndex:0] setObject:@"Any Name" forKey:@"single"] ;

作为参考,这是我在NSUserDefaults中保存的方式

+(void)storeArrayToDefaults :(NSString *)keyName objectToAdd:(NSMutableArray *)arrayData

{

    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:arrayData forKey:keyName];

    [defaults synchronize];
}

2 个答案:

答案 0 :(得分:2)

试试这个

 NSMutableArray *setDetails = [NSMutableArray arrayWithArray:[[[NSUserDefaults standardUserDefaults] arrayForKey:SETTINGS_DETAILS] mutableCopy]];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[setDetails objectAtIndex:0]];
[dict setObject:@"Any Name" forKey:@"single"];
[setDetails replaceObjectAtIndex:0 withObject:dict];

答案 1 :(得分:1)

NSUserDefaults中的所有内容都是不可变的。您创建外部容器的可变副本,但其内容仍然是不可变的。因此,要编辑它们,您需要获取可变副本,更新它然后重新插入(并重新添加到默认值)。

[[setDetails objectAtIndex:0] setObject:@"Any Name" forKey:@"single"];

更改为

NSMutableDictionary *dict = [[setDetails objectAtIndex:0] mutableCopy];
[dict setObject:@"Any Name" forKey:@"single"];
[setDetails replaceObjectAtIndex:0 withObject:dict];