2010-07-15 203 views
0

任何人都可以啓發我爲什麼我要在這段代碼中獲得EXC_BAD_ACCESS嗎?我運行了配備了Allocations和NSZombie的樂器,它說我發送了一個殭屍,但是看不到它。EXC_BAD_ACCESS for for循環

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 
    } 
} 

這裏是統計工具:
alt text http://i28.tinypic.com/24q1ixc.jpg

感謝

回答

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

從條件,col總是< 13,所以-removeObjectAtIndex:將始終運行。但是這會在前一行那[keys objectAtIndex:0]。由於myarray[row][col]與它具有相同的引用,因此它有可能被解除分配 - 這就是後來崩潰的原因。

您必須-retain保持活動狀態的對象,例如,

 myarray[row][col] = [[[keys objectAtIndex:0] retain] autorelease]; 
+0

謝謝!內存管理從來就不是最強硬的......蘋果公司的文檔因我的喜好而過分詳細 – joec 2010-07-15 09:43:22

0

在評論NSLog語句後試過了嗎?