iPhone开发 - UIImageView内存问题

时间:2010-02-12 13:40:28

标签: iphone memory uiscrollview uiimageview initwithcontentsofurl

背景

受到Apple的示例代码ScrollViewSuite的启发,我创建了一个视图控制器类,显示图片缩略图和一个选定的图片。 “选定”图片的控件层次结构如下:

--> UIView
    --> UIScrollView
        --> UIImageView

以下代码用于将UIScrollView放到视图中:

imageScrollView = [[UIScrollView alloc] initWithFrame:frame];
[imageScrollView setBackgroundColor:[UIColor clearColor]];
[imageScrollView setDelegate:self];
[imageScrollView setBouncesZoom:YES];
[[self view] addSubview:imageScrollView];

...以下代码用于配置UIImageView并将其添加到UIScrollView:

// Custom method to return a UIImage from a URL string
UIImage *image = [UIImage newImageWithContentsOfURL:imageURL];  

// first remove previous image view, if any
[[imageScrollView viewWithTag:MAIN_IMAGE_TAG] removeFromSuperview];

// set the new image view
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[imageView setDelegate:self];
[imageView setTag:MAIN_IMAGE_TAG];
[imageScrollView addSubview:imageView];
[imageScrollView setContentSize:[imageView frame].size];

// choose minimum scale so image width fits screen
float minScale  = [imageScrollView frame].size.width / [imageView frame].size.width;
[imageScrollView setMinimumZoomScale:minScale];
[imageScrollView setZoomScale:minScale];
[imageScrollView setContentOffset:CGPointZero];

// clear memory
[imageView release];
imageView = nil;

[image release];
image = nil;

这是我用来使用URL字符串获取UIImage的类别方法:

+ (UIImage *)newImageWithContentsOfURL:(NSString *)imageURL {   
    NSURL *url = [[NSURL alloc] initWithString:imageURL];
    NSData *data = [[NSData alloc] initWithContentsOfURL:url];
    UIImage *image = [[UIImage alloc] initWithData:data];
    [data release];
    [url release];

    return image;
}

问题: 加载大小为110 Kb(大约)的jpeg图像的影响是应用程序的实际内存从12 MB(大约)跳到38 MB(大约)。当我第一次看到这个时,我感到困惑。这怎么可能?呃,最终的结果是:应用程序在iPhone 3G上崩溃(偶尔)。

请注意,内存读数是使用Instruments中的Memory Monitor工具进行的 - 同时在设备上测试应用程序(而不是模拟器)。另请注意,仪器没有显示内存泄漏,静态分析器也没有指出任何可疑的内容。

我需要帮助!

2 个答案:

答案 0 :(得分:3)

它是否与jpeg被压缩的事实有关。 它可能在显示时被解压缩,因此内存量大幅增加。

1:1比例图像的尺寸是多少?

答案 1 :(得分:0)

肯定它必须是除了jpeg以外的东西,它使得它使用如此多的记忆和崩溃 - 我有一个1520x250像素的png,它滚动得很漂亮......