iOS:Instruments 显示 imageio_png_data 的大小比其实际图像大小大 300 倍

标签 ios xcode memory-management instruments xcode-instruments

我有一张只有 28KB 大小的图片: enter image description here

我使用这段代码将它添加到我的 View 中:

  UIImageView *background = [UIImageView new];
  background.frame = CGRectMake(0, 0, 1080, 1920);
  background.image = [UIImage imageNamed:@"Submit.png"];
  [self.view addSubview:background];

现在我在分配图像之前和之后使用 Instruments Allocation 和“Marking Generation”进行分析:

enter image description here

仪器表明将图像加载到内存中需要 7.92MB。 我在其他图像上也看到了同样的问题。 为什么 ImageIO_PNG_Data 为 7.92MB 而图像只有 28KB?

最佳答案

@matt 和@dan 确实很好地解释了为什么未压缩的图像在屏幕上显示时实际占用的内存是实际 PNG 图像大小的 300 倍。让这个问题更糟的是 iOS 缓存这些图像并且永远不会从缓存中释放它们,即使是在出现内存警告时也是如此。

所以这里有一种方法可以防止 iOS 上的图像缓存以节省大量内存,只需使用 imageWithContentsOfFile 而不是 imageNamed:

替换:

background.image = [UIImage imageNamed:@"Submit.png"];

与:

background.image = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/Submit.png"]];

现在 ImageIO_PNG_Data 将在 View Controller 关闭时释放。

一切都在这里: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/#//apple_ref/occ/clm/UIImage/imageNamed :

If you have an image file that will only be displayed once and wish to ensure that it does not get added to the system’s cache, you should instead create your image using imageWithContentsOfFile:. This will keep your single-use image out of the system image cache, potentially improving the memory use characteristics of your app.

关于iOS:Instruments 显示 imageio_png_data 的大小比其实际图像大小大 300 倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31952201/

相关文章:

c - R XML - 无法从内存中删除内部 C 节点

java - 静态变量的实际内存位置是什么?

ios - 一个 TableView 中的多个 NSFetchedResultsController

iphone - 创建运行脚本来打包和压缩编译库

iphone - Snow Leopard 上的 iOS SDK 4.3 安装错误

ios - 在 'window' 类型的对象上找不到属性 'BSViewController *'

c++ - 使用动态大小的内存池在多线程 C/C++ 中实现内存管理器?

ios - 为什么自定义委托(delegate)协议(protocol)包含可选值 - SWIFT

c# - AntiForgery.GetTokens : what is the purpose of the oldCookieToken parameter?

ios - 如何在WKWebView中重写urlRequest