objective objective-c xcode popup viewdidload

objective-c - objective - uiviewcontroller xcode



Error: método de mutación enviado al objeto inmutable para NSMutableArray del archivo JSON (1)

Este parece ser un problema bastante común, pero las soluciones que he analizado no resuelven el error. Estoy tratando de leer un NSMutableArray de un archivo JSON. Muchas de las sugerencias que he visto involucran el uso de mutableCopy o [NSMutableArray arrayWithArray:] pero ambas soluciones no solucionan el problema cuando se utiliza la llamada replaceObjectAtIndex: withObject: se ve a continuación. Por favor, avíseme si tiene algún consejo sobre cómo resolver este problema.

EDITAR: También me gustaría añadir que la lista de inventario es un NSMutableArray de objetos NSMutableArray.

El error exacto dice:

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

Tengo la propiedad definida de la siguiente manera en la parte superior de mi archivo de implementación:

NSMutableArray *inventoryData;

Estoy tratando de leerlo desde un archivo JSON de la siguiente manera:

- (void)readJSON { //Code to get dictionary full of saves from JSON file (overworld.json) - includes the file path on the ipad as well as //the dictionary itself NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *localPath = [[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:@"savedPaintGameData.json"]]; NSString *filePath = [localPath mutableCopy]; NSError *e = nil; // Read data from file saved previously - read the raw data from the path, then parse it into a dictionary using JSONObjectWithData NSData *RawJSON = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&e]; if (RawJSON == nil) { [self saveGameInitialize]; } else { NSMutableDictionary *localDictionary = [[NSMutableDictionary alloc] initWithDictionary:[NSJSONSerialization JSONObjectWithData:RawJSON options:NSJSONReadingAllowFragments error:&e]]; NSMutableDictionary *savedDataDictionary = [localDictionary mutableCopy]; //inventoryData = [[savedDataDictionary objectForKey:@"inventory"] mutableCopy]; inventoryData = [NSMutableArray arrayWithArray:[savedDataDictionary objectForKey:@"inventory"]]; } }

Estoy tratando de reemplazar un objeto en el índice dado de NSMutableArray como se ve aquí:

- (void)setInventoryData: (NSString *) colorKey: (int) change { // Check if inventory already contains the paint and change the amount bool foundPaint = false; int newAmount = 100; // Magic number prevents crashing @ removal check for (int i = 0; i < [inventoryData count]; i++) { NSMutableArray *object = [inventoryData objectAtIndex:i]; if ([[object objectAtIndex:0] isEqualToString:colorKey]) { newAmount = [[object objectAtIndex:1] integerValue] + change; [[inventoryData objectAtIndex:i] replaceObjectAtIndex:1 withObject:[NSNumber numberWithInt:newAmount]]; foundPaint = true; break; } } if (newAmount == 0) { [self removeInventoryColor:colorKey]; } }


El problema parece estar en la profundidad en la que está trabajando ... las versiones mutables de los contenedores que está creando solo se aplican a ese "nivel". Posteriormente, se indexa en ese nivel (es decir, se accede a un contenedor de un nivel más profundo) que aún es inmutable. Intente pasar la opción NSJSONReadingMutableContainers cuando NSJSONReadingMutableContainers el JSON por primera vez:

NSUInteger jsonReadingOptions = NSJSONReadingAllowFragments | NSJSONReadingMutableContainers; NSMutableDictionary *localDictionary = [[NSMutableDictionary alloc] initWithDictionary:[NSJSONSerialization JSONObjectWithData:RawJSON options:jsonReadinOptions error:&e]];