Domanda

okay, so di essere nuovo a obj-c, ma a tutti gli effetti i seguenti SEEMS che seguono dovrebbero funzionare:

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);

Spero che qualcuno mi possa aiutare qui, sbatto la testa contro il muro!

È stato utile?

Soluzione

songCollection era originariamente un NSMutableArray, ma poi lo hai sovrascritto con qualsiasi cosa sia restituita da [GeneralFunctions getJSONAsArray: @ " library "] . Qualunque cosa sia, probabilmente non è un array.

Per inciso, stai perdendo un array qui.

Altri suggerimenti

Consente di smontare il codice passo dopo passo.

songCollection = [[NSMutableArray alloc] init];

Alloca un nuovo NSMutableArray vuoto.

[songCollection addObject:@"test"];

Aggiunge NSString @ " test " alla canzone SongCollection di NSMutableArray

songCollection = [GeneralFunctions getJSONAsArray:@"library"];

Elimina il tuo riferimento alla matrice mutabile che hai creato (perdendo così la memoria) e ti dà un nuovo puntatore a qualcosa che non possiedi ancora.

[songCollection retain];

Bene, prendi la proprietà di songCollection. E dal momento che funziona, sai che getJSONAsArray ha restituito zero o un oggetto NSO.

NSLog(@"%@", [songCollection objectAtIndex:0]);
// Crashes here due to the array not responding to the selector. Also, the array is now empty.

Quindi chiaramente songCollection non è né nullo, né un NSArray (mutabile o meno). Controlla la documentazione o la firma di GeneralFunctions getJSONAsArray e vedi cosa restituisce effettivamente.

//NSLog(@"%@", songCollection);

Cosa significa questo output - che dovrebbe dirti cos'è effettivamente songCollection.

Supponendo di capire perché getJSONAsArray non restituisce un NSArray, è possibile convertire un NSArray in 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 "] restituisce effettivamente un NSArray?

Stai anche dimenticando di rilasciare songCollection prima di riassegnarlo a quella linea.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top