【问题标题】:copy NSUserDefaults array and edit the array复制 NSUserDefaults 数组并编辑数组
【发布时间】:2018-07-07 11:29:14
【问题描述】:

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

时,我遇到了崩溃

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

我所做的是首先在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];
}

【问题讨论】:

  • getArr 的目的是什么?两个数组实际上具有相同的数据。
  • d的类型是什么?

标签: ios objective-c


【解决方案1】:

问题是存储的字典对象是不可变的,所以你需要 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

【讨论】:

    【解决方案2】:

    问题是你只有数组被复制为可变的。但是里面的字典仍然是不可变的对象。您可以尝试制作深度可变副本,但对于您的情况,您可以执行以下操作

    for(int i = 0;i<newArray.count;i++)
    {
      //Just copy the dict as mutable and then change the value
      NSDictionary *dict  = [[newArray objectAtIndex:i] mutableCopy];
      dict["key"] = "NewValue" 
      [newArray replaceObjectAtIndex:i withObject:dict];
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-10
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 2016-03-05
      相关资源
      最近更新 更多