App Crashing: Mutating method sent to immutable object

I am trying to add an object to an NSMutableArray. Initially I assign some response data to the array, and can display it in a table view. After loading more data, it seems to be crashing when trying to add the new information to my original array.

I am using AFNetworking for this:

  • Auto layout internal error happening when a view is dismissed
  • how to draw grid lines when camera is open avcapturemanager
  • Asynchronous UITableViewCell Image Loading Using GCD
  • IOS Video Compression Swift iOS 8 corrupt video file
  • Camera has incorrect screen placement when open fullscreen modal from popover
  • Allows music playback during recording video like snapchat ios
  • [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    
        if(!_myArray){
            _myArray = [responseObject objectForKey:@"data"];
        }
        else{
            [_myArray addObject:[responseObject objectForKey:@"data"]];
        }
        [self.tableView reloadData];
    }
    

    The error I am getting is as follows

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

    Can anybody help out with this?

    4 Solutions Collect From Internet About “App Crashing: Mutating method sent to immutable object”

    The object you’re retrieving from the responseObject dictionary is most likely not an NSMutableArray, but an (immutable) NSArray. You have to create a mutable copy to be able to change it:

    //...
    if (!_myArray) {
        _myArray = [[responseObject objectForKey:@"data"] mutableCopy];
    }
    //...
    

    It sounds like AFNetworking generates immutable objects. You should call -mutableCopy instead of just assigning the result of -objectForKey: directly.

    Also are you really intending to have a bunch of nested arrays? It seems like it would make more sense if you added the contents of the response array, rather than the array itself.

    You need to make the copy of your array. After that you have to modify that array using, [NSMutableArray arrayWithArray: ]

    Your array is must be mutable array

    Use NSMutablearray instead NSArray