代码之家  ›  专栏  ›  技术社区  ›  diatrevolo

何时正确释放物体

  •  2
  • diatrevolo  · 技术社区  · 14 年前

    - (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];
    }
    

    我本以为这个程序现在已经用model完成了,但一发布就崩溃了。如果我不释放它,程序会运行,但显然内存泄漏。我做错什么了?

    2 回复  |  直到 14 年前
        1
  •  4
  •   vfn    14 年前

    代码的问题是,当您第一次进入循环时正在泄漏。

    InteractionPointModel *model = [[InteractionPointModel alloc] init];
    

    model = [interactionPointData objectAtIndex:x];
    

    上面这条线是 model 指向另一个对象,这样,前面的值就不再指向了。

    [model release];
    

    释放时会崩溃,因为释放的是一个不属于自己的值。当你得到释放,如果你进入循环,至少一次, 指向数组的最后一个对象 interactionPointData

    要修复代码,只需删除错误的内存管理。

    - (void)scrollViewDidScroll:(UIScrollView *)localScrollView {
        InteractionPointModel *model = nil;
        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];
        }
    }
    
        2
  •  2
  •   BoltClock    14 年前

    你好像在替换一个新分配的 InteractionPointModel 对象中的现有对象 interactionPointData 数组。在方法的末尾,在循环之后,您试图释放 正如您在评论中所说,数组中的一个对象是您不拥有的,这会导致崩溃。

    如果不释放它,则泄漏是由刚开始初始化的新分配的对象引起的,该对象已更改,因此不再可访问 model