从NSMutableArray释放CGMutablePathRef

时间:2011-06-14 22:28:21

标签: objective-c ios nsmutablearray

我通过NSValue将CGMutablePathRefs存储在NSMutableArray中。

像这样:

CGMutablePathRef path = CreateMutablePath();
[self.myArray addObject:[NSValue valueWithPointer:path]];

在我的dealloc中,我试过这个:

- (void)dealloc
{
    [super dealloc];

    for (int i = 0; i < self.myArray.count;) {

        NSValue *currentPath = [self.myArray objectAtIndex:i];

        CGMutablePathRef path = (CGMutablePathRef)[currentPath pointerValue];

        CGPathRelease(path);
    }

    self.myArray = nil;

}

然而,当我运行它时,我得到以下异常:

malloc: *** error for object 0x16b250: pointer being freed was not allocated

有人可以向我解释为什么会这样,以及我应该如何正确发布CGMutablePathRefs?

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

[super dealloc] 必须始终是dealloc 的最后一行。

希望以这种方式释放数组中的对象。让数组管理内存。

即:

CGMutablePathRef path = CreateMutablePath();
[self.myArray addObject:[NSValue valueWithPointer:path]];
CGPathRelease(path);

- (void) dealloc
{
   self.myArray = nil;
   [super dealloc];
}

答案 1 :(得分:0)

虽然我很欣赏Bavarious'和bbum关于[超级dealloc]的位置的修正,这不是我的问题。在我的实际代码中,我在一个单独的方法中调用“释放”代码。我把它放在dealloc里面,因为我试图简化我的问题并错误地将它粘贴在错误的地方。

我认为问题不在于代码,而在于环境问题。我把代码带到了另一台机器上,并没有遇到任何问题。我重新启动了原始机器,它现在也表现正常。我想我处于一种奇怪的状态或什么的。