【发布时间】:2011-01-16 03:55:59
【问题描述】:
背景:
受 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 工具获取的 - 在设备(而不是模拟器)上测试应用程序时。另请注意,Instruments 没有显示内存泄漏,Static Analyzer 也没有指出任何可疑之处。
我需要帮助!
【问题讨论】:
-
将 1 x 110kb 图像加载到 imageView 后崩溃?
-
是的。加载到 imageView 时 110 Kb 的图像使实际内存从 12 MB 拍摄到 38 MB。
标签: iphone memory uiscrollview uiimageview initwithcontentsofurl