PeterK
PeterK

Reputation: 4301

NSMutableArray addObject mistake

I can not addObject into 'easyQArray' (NSMutableArray). It did work when I had the array defined locally but when I moved the declaration into the .h file it does not work anymore.

The app crash ofc as I try to access an index in the array that does not exist:

// Create question arrays
if (easyPlayers > 0) {
    for (int XX = 0; XX < easyQuestions; XX++) {
        [easyQArray addObject: [myArray objectAtIndex: easyQStartPos]];
        NSLog(@"myArray: %@", [myArray objectAtIndex: easyQStartPos]);
        NSLog(@"easyQArray: %@", easyQArray);
        easyQStartPos = easyQStartPos + 1;
    }
}

Output:

2010-12-28 15:52:57.636 XX_v2[11582:207] myArray: 205
2010-12-28 15:52:57.636 XX_v2[11582:207] easyQArray: (null)
2010-12-28 15:52:57.636 XX_v2[11582:207] myArray: 71
2010-12-28 15:52:57.637 XX_v2[11582:207] easyQArray: (null)
2010-12-28 15:52:57.637 XX_v2[11582:207] myArray: 94
2010-12-28 15:52:57.638 XX_v2[11582:207] easyQArray: (null)
2010-12-28 15:52:57.638 XX_v2[11582:207] myArray: 133
2010-12-28 15:52:57.638 XX_v2[11582:207] easyQArray: (null)
2010-12-28 15:52:57.639 XX_v2[11582:207] myArray: 142
2010-12-28 15:52:57.640 XX_v2[11582:207] easyQArray: (null)

Upvotes: 2

Views: 2128

Answers (3)

Neilvert Noval
Neilvert Noval

Reputation: 1695

It should work even if you moved it .h.
Make sure you initialize your easyQArray. And make sure you initialized it as NSMutableArray.
Initialization should take place before you do the addObject in [easyQArray addObject: [myArray objectAtIndex: easyQStartPos]];

Upvotes: 0

Julien
Julien

Reputation: 3477

easyQArray is defined but where is it allocated? (my guess is that it isn't as your log shows that it's nil)

The likely missing line:

easyQArray = [[NSMutableArray alloc] init];

Upvotes: 0

Henrik P. Hessel
Henrik P. Hessel

Reputation: 36617

Seems that you didn't even init your Array. From your description it sounds like your declared it as a property so calling alloc / init in your class init method should fix your problem.

easyQArray = [[NSMutableArray alloc] init];  

Upvotes: 12

Related Questions