0
votes

I am attempting to delete an object for a particular key in an NSMutableDictionary but the application crashes when trying to do so. Here is my code:

    NSArray *allWebDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
    self.results = [[NSMutableArray alloc] initWithArray:allWebDictionary];

    for (NSMutableDictionary *dic2 in self.results) {
        NSMutableArray *incidents = [dic2 valueForKey:@"incidents"];
        for (NSMutableDictionary *incident in incidents) {
            [incident removeObjectForKey:@"type"];
        }
    }

My app crashes with the following log:

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

Any ideas? Thanks in advance!

1
Have you tried specifying NSJSONReadingMutableContainers with options instead of 0? Always better to use the provided constants. Also, stick in a break point and check to see the real data type after you get the values. - DBD

1 Answers

0
votes

You made a mutable copy of the array, but the dictionary which is in the array is still immutable.

You need mutable containers.

Replace

NSArray *allWebDictionary = [NSJSONSerialization JSONObjectWithData:webData
                                                            options:0
                                                              error:nil];

with

NSMutableArray *allWebDictionary = [NSJSONSerialization JSONObjectWithData:webData
                                                                   options:NSJSONReadingMutableContainers
                                                                     error:nil];