ios - 在 UIImage 和 UIImageViews 中释放 Swift 中的内存

标签 ios swift uiimageview uiimage autorelease

我正在开发一个包含多个 View 的应用程序。每个 View 包含几个由 UIImageView.animate 形成的动画。我遇到的问题是,每次我打开一个新的 View 时,内存都没有减少,在 iPhone 4 上增加到 320 Mb,重新随机出现内存错误“因内存错误而终止”。我找不到如何在 Swift 中自动释放内存,因为在 Objective-C 中,如果我能看到它更适合使用 imageWithContentOfFile 而不是 named: ...

我用它来将图像添加到 UIImage 对象:

var leftCorner: UIImage =  UIImage(named: "navegacio_esquerra")!

要在 UIImageView.animationImages 中添加图像数组,我使用这个:

var thirdSisterHeadList: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 33, 32, 33, 34, 33, 32, 33, 34, 33, 32, 33, 34, 33, 32, 33, 34, 33, 66, 67, 68]

        var thirdSisterHeadImageList: [UIImage] = []

        for i in thirdSisterHeadList{
            var imageName = "pantalla_12_03_caps_c_\(i).png"
            thirdSisterHeadImageList += [UIImage(named: imageName)!]
        }
thirdSisterHead.animationImages = thirdSisterHeadImageList

最佳答案

这条评论没有意义

I can not find how to autorelease memory in Swift, since in Objective-C if I could see it's more advisable to use imageWithContentOfFile instead of named:.

Swift 和 ObjC 管理内存的方式相同。对于这种工作,您肯定希望使用 named:,因为它允许系统为您执行更好的内存管理。当内存紧张时,它可以自动清除不需要的表示。

从 Instruments 中的 Allocations 工具开始。确保这些图像确实是您的内存所在的位置。情况很可能如此,但对于内存分析,您需要的是数据,而不是猜测。

您多次使用相同的图片。这可能没问题,但你应该验证 pantalla_12_03_caps_c_33.png 的每个实例实际上是相同的 UIImage(这真的应该自动为你工作,所以我不强烈怀疑这里有问题)。

要为图像设置动画,需要将它们全部解码到内存中。即便如此,在 iPhone 4 上存储 30 张图像需要 320MB 的空间听起来还是很多。每张图片约 10MB。全屏 iPhone 4 图像应该更像是 2MB (640*960*4)。如果您使用的是非常高分辨率的图像,您可能希望为不同的设备提供多种分辨率,这样它就不必处理太多会被丢弃的数据。

内存未被回收这一事实几乎肯定意味着您的 View 未被释放。这表明您有一个保留循环,或者您可能一直调用 addSubview: 来添加一个 ImageView 而不删除旧的 ImageView (这是一个很常见的错误)。在您的 View Controller 中覆盖 dealloc 并确保它在您期望的时候消失。确保您没有在该 View Controller 之外的某处按住 thirdSisterHead

不相关的旁注:您的 for-in 循环确实很难做到这一点。这段代码可以简化并将所有变量替换为常量,并且无需为 += 创建临时 [UIImage]:

let thirdSisterHeadList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 33, 32, 33, 34, 33, 32, 33, 34, 33, 32, 33, 34, 33, 32, 33, 34, 33, 66, 67, 68]
let thirdSisterHeadImageList = thirdSisterHeadList.map { 
    UIImage(named: "pantalla_12_03_caps_c_\($0).png")! 
}
self.thirdSisterHead.animationImages = thirdSisterHeadImageList

关于ios - 在 UIImage 和 UIImageViews 中释放 Swift 中的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28719543/

相关文章:

iphone - 子级 View Controller 未收到 NSNotification

arrays - 根据阵列中每个I时间的持续时间播放快速声音

ios - 如何在 Swift 中拆分 JSON 字符串?

iOS UIImageView 内存未在 ARC 上释放

ios - 使用 XMSegmentedControl 更改 TableViewCell

ios - 是否可以使用 PDF 远程数据初始化 UIImage?

iphone - 突出显示单元格时更改为自定义背景

xcode - 执行从 Xib 到 ViewController 的转场

ios - 如何像邮件一样在 UITextView 中显示图像并使其居中

ios - 拖动图像以适合正确的边界框