I am trying to better understand when to properly release an object in a fairly memory intensive program. My current doubt arises from the following bit of code:
- (void)scrollViewDidScroll:(UIScrollView *)localScrollView
{
InteractionPointModel *model = [[InteractionPointModel alloc] init];
for (int x=0; x<totalInteractionPoints; x++) {
model = [interactionPointData objectAtIndex:x];
CGPoint oldCenter = model->worldLocation;
CGPoint newCenter;
newCenter.x = oldCenter.x * [localScrollView zoomScale];
newCenter.y = oldCenter.y * [localScrollView zoomScale];
[[interactionPoints objectAtIndex:x] setCenter:newCenter];
}
[model release];
}
I would have thought that the program was done with model by now, but it crashes upon release. If I don’t release it, the program runs, but obviously with a memory leak. What am I doing wrong?
The problem with your code is that you are leaking when you first enter on the loop.
The line above is allocating an object that won’t be used.
The line above makes
modelpoint to a different object, and so, the previous value is not pointed anymore.You get the crash when releasing because you are releasing a value that you don’t own. When you get at release, if you enter on the loop, at least once,
modelis pointing to the last object of the arrayinteractionPointData.To fix your code, you need only to remove the wrong memory management.