gpt4 book ai didi

ios - UIImage imageNamed内存泄漏

转载 作者:可可西里 更新时间:2023-11-01 04:30:18 26 4
gpt4 key购买 nike

我试图理解为什么在 UIImage 和 UIImageView 的非常基本的实现中会出现内存泄漏。

在那种情况下我没有使用 ARC(正确禁用)。

我的代码非常简单:

UIImage *image = [UIImage imageNamed:@"my_image.jpg"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[[self view] addSubview:imageView];
[imageView release];

我在 UIViewController 的 viewDidLoad: 方法中实现这段代码。

通过调用 UIImage 的方法 imageNamed:,我知道我会得到一个我不拥有的对象/一个自动释放对象。该对象也将由刚刚实例化的 UIImageView 对象保留。所以我拥有所有权的唯一对象是 UIImageView。

在使用 Memory Leaks Instruments 运行这个应用程序后,我得到了这个报告:

enter image description here

我听说有运行的缓存系统,但我不应该有内存泄漏,因为一些数据被缓存了。

这是对缓存解释的答案的引用: https://stackoverflow.com/a/2930567/1154501

提前致谢!

编辑:也尝试使用 ARC,我遇到了同样的问题。

最佳答案

[UIImage imageNamed:] 由操作系统管理。取消分配从此方法创建的 UIImage 可能会释放已分配的内存。如果您有大量图像或用户生成的内容,您应该使用 [UIImage imageWithContentsOfFile:][UIImage imageWithData:]

如果您使用 [UIImage imageNamed:] 创建过多图像,您的应用可能会因为内存占用而被 iOS 终止。我制作了一个示例应用程序来向自己证明这一点,请在此处查看更多信息:iOS UIImage storage formats, memory usage and encoding / decoding

关于ios - UIImage imageNamed内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19437285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com