Question

okay, I know I am new to obj-c, but for all intents and purposes the following below SEEMS like it should work:

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

I'm hoping someone can help me here, I'm banging my head against the wall!

Was it helpful?

Solution

songCollection was originally an NSMutableArray, but then you overwrote it with whatever is returned from [GeneralFunctions getJSONAsArray:@"library"]. Whatever that is, it's probably not an array.

Incidentally, you're leaking an array here.

OTHER TIPS

Lets take your code apart step by step.

songCollection = [[NSMutableArray alloc] init];

Allocates a new empty NSMutableArray.

[songCollection addObject:@"test"];

Adds the NSString @"test" to the NSMutableArray songCollection

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

Throws away your reference to the mutable array you created (thus leaking memory) and gives you a new pointer to something that you do not own yet.

[songCollection retain];

Thats good, you take ownership of songCollection. And since this works, you know that getJSONAsArray returned either nil or an NSObject.

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

So clearly songCollection is neither nil, nor an NSArray (mutable or otherwise). Check the documentation or signature for GeneralFunctions getJSONAsArray and see what it actually returns.

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

What does this output - that should tell you what songCollection actually is.

Assuming you figure out why getJSONAsArray is not returning an NSArray, you can convert an NSArray to an NSMutableArray with

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

or

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

Does [GeneralFunctions getJSONAsArray:@"library"] actually return an NSArray?

You're also forgetting to release songCollection before you re-assign it with that line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top