Malloc错误:在OBJC中双重免费

时间:2011-03-19 18:09:59

标签: iphone

我正在使用一组NSNumbers,我有一种方法可以根据按下的按钮填充它们;

 - (NSMutableArray *)addNumberToArray:(int)numPressed andWithGuessArray:(NSMutableArray *)guessArray andWithActiveIndex:(int)activeIndex {
NSNumber *numberPressed = [NSNumber numberWithInt:numPressed];
switch (numPressed) {
    case 1:
        [guessArray replaceObjectAtIndex:activeIndex withObject:numberPressed];
        break;

    case 2:
        [guessArray replaceObjectAtIndex:activeIndex withObject:numberPressed];
        break;

    case 3:
        [guessArray replaceObjectAtIndex:activeIndex withObject:numberPressed];
        break;

    case 4:
        [guessArray replaceObjectAtIndex:activeIndex withObject:numberPressed];
        break;

    case 5:
        [guessArray replaceObjectAtIndex:activeIndex withObject:numberPressed];
        break;

    case 6:
        [guessArray replaceObjectAtIndex:activeIndex withObject:numberPressed];
        break;

    case 7:
        [guessArray replaceObjectAtIndex:activeIndex withObject:numberPressed];
        break;

    case 8:
        [guessArray replaceObjectAtIndex:activeIndex withObject:numberPressed];
        break;

    case 9:
        [guessArray replaceObjectAtIndex:activeIndex withObject:numberPressed];
        break;

    default:
        break;
}
[numberPressed release];

for (int i = 0; i < 4; i++) {
    NSLog(@"%i",[[guessArray objectAtIndex:i]intValue]);
}
NSLog(@"----");

return guessArray;

}

然后我有一个删除数组中所有数字的方法。

- (void)deleteAll:(id)sender {
NSLog(@"%@",guessArray);
for (int i = 0; i < numbersInAns; i++) {
    [guessArray replaceObjectAtIndex:i withObject:[NSNumber numberWithInt:0]];

}

activeIndex = 0;
for (int i = 0; i < 4; i++) {
        NSLog(@"%i",[[guessArray objectAtIndex:i]intValue]);
}

}

当我填充数组,清除它,再次填充它并尝试再次清除它时,会出现问题。

2011-03-19 13:58:43.492 BombDefusal [4711:207](     2,     2,     3,     3 )//这是在它清除之前的数组中是什么,这些都是NSNumbers

BombDefusal(4711,0xa096a540)malloc: *对象0x4e0cc40的错误:双倍免费 * 在malloc_error_break中设置断点以进行调试

(gdb)print-object 0x4e0cc40

2

解决

1 个答案:

答案 0 :(得分:2)

您收到的错误消息显示“在malloc_error_break中设置断点以进行调试”。你试过吗?

您在release对象上调用numberPressed,但您没有retain它。 NSNumber类方法numberWithInt:向您返回一个自动释放的对象。 release调用是不必要且不正确的。

除此之外,你的switch语句中的每个条目都包含完全相同的代码 - 你为什么要编写switch语句?你可以用一行替换整个块:

[guessArray replaceObjectAtIndex:activeIndex withObject:numberPressed];