对象泄漏:在UIScrollView中添加和删除UIImageView

时间:2010-11-06 17:13:15

标签: iphone memory-leaks

我正在尝试动态添加图像到ScrollView。在添加之前,我检查ScrollView中是否有任何子视图,并在for循环中删除它们。

当我发布imageview时,我收到一个运行时错误,指出我正在尝试访问一个已解除分配的实例。如果我删除了release语句,应用程序将正确运行,但“build and analyze”显示泄漏,因为imageview的引用计数没有减少..

if ([scrollView.subviews count]>0){
    for (int i=0; i<[scrollView.subviews count]; ++i) {
        [[scrollView.subviews objectAtIndex:i] removeFromSuperview];
    }
}

//Making a scroller with results
int scrollWidth = 0.0f;
int scrollHeight = 0.0f;
for (int i = 0; i<previewImages.count;++i)
{
    UIImage *image=[previewImages objectAtIndex:i];
    scrollWidth = scrollWidth + image.size.width;  // Width of all the images
    if (image.size.height > scrollHeight)scrollHeight= image.size.height; // Maximum image height
    [image release];
}

float xC = 0.0f;
for (int i=0; i<previewImages.count; ++i) { 

    UIImage *image=[previewImages objectAtIndex:i];
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(xC, 0.0f, image.size.width, image.size.height)];
    UILabel *subScript = [[UILabel alloc] initWithFrame:CGRectMake(xC, image.size.height-30.0f, image.size.width,30.0f)];

    subScript.textColor = [UIColor whiteColor];
    subScript.backgroundColor = [UIColor colorWithWhite:0.5f alpha:0.5f];
    subScript.text = [imagePaths objectAtIndex:i];

    imageview.image = image;

    xC = xC + image.size.width;
    [image release];
    [scrollView addSubview:imageview];
    [imageview release];
    [scrollView addSubview:subScript];
    [subScript release];
}
[scrollView setContentSize:CGSizeMake(scrollWidth , scrollHeight)];

有关内存泄漏的任何建议或将数组中的视图添加到scrollView中的一般最佳做法都非常感谢!

1 个答案:

答案 0 :(得分:1)

if ([scrollView.subviews count]>0){
    for (int i=0; i<[scrollView.subviews count]; ++i) {
        [[scrollView.subviews objectAtIndex:i] removeFromSuperview];
    }
}

是错误的,因为您要从子视图数组中删除子视图。反向迭代会解决这个问题,但我建议将视图保持在单独的数组中。