Releasing CGMutablePathRef from NSMutableArray
I am storing CGMutablePathRefs inside of a NSMutableArray via NSValue.
Like so:
CGMutablePathRef path = CreateMutablePath();
[self.myArray addObject:[NSValue valueWithPointer:path]];
In my dealloc, I have tried this:
- (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;
}
However, when I run this, I get the following exception:
malloc: *** error for object 0x16b250: pointer being freed was not allocated
Can someone please explai开发者_StackOverflow中文版n to me why this is and how I should correctly release the CGMutablePathRefs?
Any help is appreciated.
[super dealloc]
must always be the last line of your dealloc
.
You do not ever want to release objects in an array in that fashion. Let the array manage the memory.
I.e.:
CGMutablePathRef path = CreateMutablePath();
[self.myArray addObject:[NSValue valueWithPointer:path]];
CGPathRelease(path);
And:
- (void) dealloc
{
self.myArray = nil;
[super dealloc];
}
While I appreciate Bavarious' and bbum's correction about the placement of the [super dealloc] that wasn't really my problem. In my actual code, I am calling the "releasing" code in a separate method. I placed it inline in dealloc here because I was trying to simplify my question and mistakenly pasted it in the wrong place.
I think the problem wasn't in code, but an environmental issue. I brought the code over to a different machine and did not experiencing any problems. I rebooted the original machine and it too is behaving correctly now. I guess I was in a weird state or something.
精彩评论