首页 > 解决方案 > 复制 NSUserDefaults 数组并编辑数组

问题描述

当我替换 NSMutableArray 中的值并且消息是

“由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'”

我正在做的是首先存储一个数组NSUserDefaults,然后获取数组。之后,我正在编辑该数组的副本。

NSMutableArray *getArr = [[NSUserDefaults standardUserDefaults] valueForKey:@"List"];
NSMutableArray *newArray = [[NSMutableArray alloc]initWithArray:getArr copyItems:YES];

现在我正在替换特定索引处的新数组的值

for(int i = 0;i<newArray.count;i++)
{
  NSDictionary *dict  = [newArray objectAtIndex:i];
  dict["key"] = "NewValue" 
  [newArray replaceObjectAtIndex:i withObject:d];
}

标签: iosobjective-c

解决方案


问题是存储的字典对象是不可变的,所以你需要init一个带有它的内容的可变对象,做这个工作然后再次保存它看这个例子

NSMutableArray*old= [NSMutableArray new];

[old addObject:@{@"key":@"value"}];

[[NSUserDefaults standardUserDefaults] setObject:old forKey:@"www"];

NSMutableArray*edited = [[[NSUserDefaults standardUserDefaults] objectForKey:@"www"] mutableCopy];

NSMutableDictionary*dic = [[NSMutableDictionary alloc] initWithDictionary:[edited objectAtIndex:0]];

dic[@"key"] = @"value2";

[edited replaceObjectAtIndex:0 withObject:dic];

[[NSUserDefaults standardUserDefaults] setObject:edited forKey:@"www"];

NSMutableArray*vvv = [[NSUserDefaults standardUserDefaults] objectForKey:@"www"];

NSLog(@"%@",vvv); /// key:value2

推荐阅读