0

Fairly new to this. I am trying to add some value/keys to an array that already has value/keys.

The itemsArray contains the json and is derived from the variable json which is a parameter passed to the method from a rest api call.

This is the code I am using and it aborts (at [i setobject] with [__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'

NSMutableDictionary  *itemsArray = [json objectForKey:@"items"];
for ( NSMutableDictionary *i in itemsArray) {      
     [i setObject:@"FirstValue" forKey:@"parents"];                       
 }

All this should do is add in the key called parents for each item in the dictionary.

Now if I hard code the value/keys to the mutable dictionary itemsArray - it works fine. Its just when I use the variable json which is passed as a parameter and obtained from a call to a rest api. So the issue is likely that itemsArray contains a immutable json object even though itemsArray is mutable.

The question I have is how do I make the json object mutable (assuming that will cure it) so it will work. ?

RayT
  • 3
  • 2

2 Answers2

0

You have the answer right in the error message: itemsArray is a NSDictionary not an NSMutableDictionary. See the answer to What is an NSCFDictionary? for more details.

How did you create json? You need to make sure it contains an NSMutableDictionary for the key @"items".

Community
  • 1
  • 1
Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
0

You will need to create a mutable dictionary from your itemsArray. Something like:

NSMutableDictionary *mutableDictionary = [i mutableCopy];

You can then add objects to it as you'd like.

joelg
  • 1,094
  • 9
  • 19