为什么我的floodfill算法中的objectAtIndex会出现exc_bad_access错误

时间:2013-02-02 18:56:05

标签: iphone objective-c exc-bad-access flood-fill

我有一个洪水填充功能:

-(void) fillArea :(int) fillNum x:(int) xSpot y:(int) ySpot
{
    int gridValue = 1;
    int gridCount = [theGrid count];
    [[theGrid objectAtIndex:(xSpot+ySpot*120)] getValue:&gridValue];

    if (gridValue != 0) {
        return;
    }
    [theGrid replaceObjectAtIndex:(xSpot + ySpot*120) withObject:[NSNumber numberWithInt:fillNum]];
    [self fillArea:fillNum x:(xSpot+1) y:(ySpot)];
    [self fillArea:fillNum x:(xSpot+1) y:(ySpot-1)];
    [self fillArea:fillNum x:(xSpot)   y:(ySpot-1)];
    [self fillArea:fillNum x:(xSpot-1) y:(ySpot-1)];
    [self fillArea:fillNum x:(xSpot-1) y:(ySpot)];
    [self fillArea:fillNum x:(xSpot-1) y:(ySpot+1)];
    [self fillArea:fillNum x:(xSpot)   y:(ySpot+1)];
    [self fillArea:fillNum x:(xSpot+1) y:(ySpot+1)];

    return;
}

theGridNSMutableArray的整数(01)。它只是一个 1D数组,通过将ySpot乘以120(网格的宽度)来模拟 2D数组。我检查了gridCount,它等于9600

但是,我在exc_bad_access获得[[theGrid objectAtIndex:(xSpot+ySpot*120)] getValue:&gridValue]。发生这种情况时,我会检查xSpotySpot,并且每次都知道(xSpot+ySpot*120) < 9600。所以我知道并不是因为我试图访问索引在我的数组之外的对象。

另外,在我的tick函数中,我运行了代码:

int gVal = 1;
int gIndex = 0;
while (gIndex < [theGrid count]) {
    [[theGrid objectAtIndex:gIndex] getValue:&gVal];
    gIndex += 1;
}

我没有收到exc_bad_access错误。请帮我弄清楚为什么我会收到exc_bad_access错误。

编辑:

我拆分[[theGrid objectAtIndex:(xSpot + ySpot * 120)] getValue:&amp; gridValue];成:

id object = [theGrid objectAtIndex:(xSpot+ySpot*widthInGridSize)];
gridValue = [object intValue];

我仍然得到了exc_bad_access,它说它已经上线了:     gridValue = [object intValue];

所以我认为这意味着对象已经被释放了?我不明白这是怎么回事。我认为不需要以任何方式保留,因为它们只是整合。另外我认为在数组中添加一个对象会自动保留它,所以为什么我的int会被释放。

在调试部分中,object的值相等:(_ NSCFNumber *)0x005aec80(int)0

1 个答案:

答案 0 :(得分:0)

根据评论 - 这实际上不是一个出界问题,而是你从'theGrid'中撤出的对象是假的(已经发布)。将其分成多行确认;并在您的调试设置中打开“僵尸”。干杯!