views:

18

answers:

2

Hi

Can anyone enlighten me as to why i'm getting an EXC_BAD_ACCESS on this chunk of code? I ran Instruments with Allocations and NSZombie enabled, and it said i messaged a zombie, but can't see whats up with it.

NSMutableArray *keys = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource: @"keys" ofType:@"plist"]];

//format: row, col
id myarray[4][13];

for (int row = 0; row<4; row++){
    for (int col = 0; col<13;col++) {
        myarray[row][col] = [keys objectAtIndex:0];
        if (col < 13) 
            [keys removeObjectAtIndex:0];
    }
}

for (int row = 0; row<4; row++){
    for (int col = 0; col<13;col++) {

        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        aButton.frame = CGRectMake(5+col*65,5+row*65, 60, 60);
        NSLog(@"%@",myarray[row][col]);
        [aButton setTitle:myarray[row][col] forState:UIControlStateNormal];
        [aButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];         

        [keyboardView addSubview: aButton];
        NSLog(@"%@",myarray[row][col]); //I think it is this NSLog causing problem
    }
}

Here are the Statistics from Instruments:
alt text

Thanks

+2  A: 
        myarray[row][col] = [keys objectAtIndex:0];
        if (col < 13) 
            [keys removeObjectAtIndex:0];

From the condition, col is always < 13, so -removeObjectAtIndex: will always be run. But this will -release that [keys objectAtIndex:0] in the previous line. Since myarray[row][col] shares the same reference with it, there is a chance it be deallocated — and that's the cause of the crash later.

You have to -retain the object to keep it alive, e.g.

        myarray[row][col] = [[[keys objectAtIndex:0] retain] autorelease];
KennyTM
Thank you! Memory management was never strongest suit... the Apple docs go into too much detail for my liking
joec
A: 

Have tried after commenting the NSLog statements?

Reena