Pregunta

I have an array structure as follows:

NSMutableArray topArray{
    NSMutableArray middleArray{
        NSMutableArray lowerArray{
            NSMutableDictionary dict{
            }
        }
    }
}

The array structure is filled with some data that I retrieve from the web is JSON format.

I am trying to edit one of the objects in the NSMutableDictionary as follow:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *lowerArray = [[self middleArray] objectAtIndex:[indexPath section]];
    NSMutableDictionary *dict = [lowerArray objectAtIndex:[indexPath row]];

    [dict setObject:[NSNumber numberWithInt:1] forKey:@"key"];

    [[self tableView] reloadData];
}

The data within each of the arrays is correct (I have checked with print statements), however, when I try to change the object in the dict I get the following error: reason:

'-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'

I need the object in the dictionary to be changed within the array structure.

Could this be an issue with the JSON data since when topArray is first initialised with the JSON data the middle and lower arrays are in the form of just NSArray's?

Sorry if this is confusing, I will try to clarify more if you have any questions.

Thanks in advance for your help.

¿Fue útil?

Solución

If you're using NSJSONSerialization, you can pass NSJSONReadingMutableContainers to the options parameter of +JSONObjectWithData:options:error:, and all of the parsed dictionaries and arrays will be mutable.

NSMutableArray *topArray = [NSJSONSerialization JSONObjectWithData:webServiceData 
                                                           options:NSJSONReadingMutableContainers 
                                                             error:nil];

Otros consejos

Just use NSMutableDictionary class instead of just NSDictionary for the moduleDict variable. It is easily done when parsing JSON objects. If no - create one like this:

NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary: moduleDict];

I doubt that you are really dealing with NSMutableDictionary on the lowest level. Do you have the output from these print statements for us?

Usually the structures generated by JSON deserialisation are of immutable type. And that is exactly what your error message is telling.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top