开发者

EXC_BAD_ACCESS in for loop

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:

EXC_BAD_ACCESS in for loop

Thanks


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


Have tried after commenting the NSLog statements?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜