0
votes

I am getting crash when i am replacing the value in NSMutableArray and the message is

"Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'"

What I am doing is first store an array in NSUserDefaults and then get the array . After that i am editing the copy of that array .

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

And Now I am replacing the value of new Array at particular index

for(int i = 0;i<newArray.count;i++)
{
  NSDictionary *dict  = [newArray objectAtIndex:i];
  dict["key"] = "NewValue" 
  [newArray replaceObjectAtIndex:i withObject:d];
}
2
what is the purpose of getArr? Both array actually have same data.Shamim Hossain
what is the type of d?Shamim Hossain

2 Answers

2
votes

The problem is that the stored dictionary object is immutable , so you need to init a mutable one with it's content , do the job then save it again see this example

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
0
votes

The problem is that you have only array copied as mutable. But dictionaries inside are still immutable objects. You can try making a deep mutable copy but for your case you can just do the following

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];
}