Pergunta

Tudo bem, eu sei que eu sou novo para obj-c, mas para todos os efeitos, o seguinte abaixo parece que ele deve 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);

Eu estou esperando que alguém pode me ajudar aqui, eu estou batendo a cabeça contra a parede!

Foi útil?

Solução

songCollection era originalmente um NSMutableArray, mas então você substituiu-o com o que é retornado de [GeneralFunctions getJSONAsArray:@"library"]. Seja lá o que é, provavelmente não é um array.

A propósito, você está vazando um array aqui.

Outras dicas

Vamos dar o seu código para além passo a passo.

songCollection = [[NSMutableArray alloc] init];

aloca um novo vazio NSMutableArray.

[songCollection addObject:@"test"];

Adiciona o NSString @ "teste" para o NSMutableArray songCollection

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

joga fora sua referência à matriz mutável você criou (memória vazando assim) e dá-lhe um novo ponteiro para algo que você não possui ainda.

[songCollection retain];

Isso é bom, você se apropriar de songCollection. E uma vez que isso funciona, você sabe que getJSONAsArray voltou seja nulo ou um NSObject.

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

Então, claramente songCollection é nem nulo, nem um NSArray (mutável ou de outra forma). Verifique a documentação ou assinatura para GeneralFunctions getJSONAsArray e ver o que ele realmente retorna.

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

O que esta saída -. Que deve dizer-lhe o que songCollection é realmente

Assumindo que você descobrir por que getJSONAsArray não está retornando um NSArray, você pode converter um NSArray a um NSMutableArray com

songCollection = [[GeneralFunctions getJSONAsArray:@"library"] mutableCopy];
// You now own songCollection

ou

songCollection = [[NSMutableArray alloc] init];
// You now own songCollection
[songCollection addObjectsFromArray:[GeneralFunctions getJSONAsArray:@"library"];

O [GeneralFunctions getJSONAsArray: @ "biblioteca"]? Realmente retornar um NSArray

Você também está esquecendo a liberar songCollection antes de voltar a atribuí-lo com essa linha.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top