NSMutableArray no responde al selector objectAtIndex
-
05-07-2019 - |
Pregunta
está bien, sé que soy nuevo en obj-c, pero para todos los propósitos y propósitos, a continuación parece que debería funcionar:
songCollection = [[NSMutableArray alloc] init];
[songCollection addObject:@"test"];
//Array is init, and I can see it in the debugger.
songCollection = [GeneralFunctions getJSONAsArray:@"library"];
// I can see the expected data in the debugger after this.
[songCollection retain];
NSLog(@"%@", [songCollection objectAtIndex:0]);
// Crashes here due to the array not responding to the selector. Also, the array is now empty.
//NSLog(@"%@", songCollection);
NSArray * songList = [songCollection objectAtIndex:1];
NSLog(@"%@", songList);
Espero que alguien pueda ayudarme aquí, ¡estoy golpeando mi cabeza contra la pared!
Solución
songCollection
fue originalmente un NSMutableArray, pero luego lo sobrescribió con lo que sea devuelto por [GeneralFunctions getJSONAsArray: @ " library "]
. Sea lo que sea, probablemente no sea una matriz.
Por cierto, estás perdiendo una matriz aquí.
Otros consejos
Vamos a separar tu código paso a paso.
songCollection = [[NSMutableArray alloc] init];
Asigna un nuevo NSMutableArray vacío.
[songCollection addObject:@"test"];
Agrega la prueba NSString @ " " a la colección de canciones de NSMutableArray
songCollection = [GeneralFunctions getJSONAsArray:@"library"];
elimina su referencia a la matriz mutable que creó (por lo tanto, pierde memoria) y le da un nuevo puntero a algo que aún no posee.
[songCollection retain];
Eso es bueno, te apropias de songCollection. Y como esto funciona, sabes que getJSONAsArray devolvió nil o un NSObject.
NSLog(@"%@", [songCollection objectAtIndex:0]);
// Crashes here due to the array not responding to the selector. Also, the array is now empty.
Claramente, songCollection no es nulo, ni NSArray (mutable o no). Consulte la documentación o la firma de GeneralFunctions getJSONAsArray y vea lo que realmente devuelve.
//NSLog(@"%@", songCollection);
¿Qué hace esta salida? Eso debería decirte qué es realmente SongCollection.
Suponiendo que descubras por qué getJSONAsArray no devuelve un NSArray, puedes convertir un NSArray en un NSMutableArray con
songCollection = [[GeneralFunctions getJSONAsArray:@"library"] mutableCopy];
// You now own songCollection
o
songCollection = [[NSMutableArray alloc] init];
// You now own songCollection
[songCollection addObjectsFromArray:[GeneralFunctions getJSONAsArray:@"library"];
¿[GeneralFunctions getJSONAsArray: @ " library "] realmente devuelve un NSArray?
También te olvidas de lanzar songCollection antes de volver a asignarlo con esa línea.