如何在Swift中从图像数组中释放图像

是否有一个“核select”从图像arrays释​​放图像? 我想玩第一个animation1(ImageSet1),然后在完成块中删除这个animation,然后加载并播放第二个animation2(ImageSet2),等等:洗,冲洗,重复 – 你明白了:)

首先,我定义了我的ViewController的实例variables:

var animation1: [UIImage] = [] var animation2: [UIImage] = [] var animation3: [UIImage] = [] 

然后我为每个animation创build一个animation数组:

 func createImageArray(total: Int, imagePrefix: String) -> [UIImage]{ var imageArray: [UIImage] = [] for imageCount in 0..<total { let imageName = "\(imagePrefix)-\(imageCount).png" let image = UIImage(named: imageName)! imageArray.append(image) } return imageArray } 

然后我设置animation值:

 func animate(imageView: UIImageView, images: [UIImage]){ imageView.animationImages = images imageView.animationDuration = 1.5 imageView.animationRepeatCount = 1 imageView.startAnimating() } animation1 = createImageArray(total: 28, imagePrefix: "ImageSet1") animation2 = createImageArray(total: 53, imagePrefix: "ImageSet2") animation3 = createImageArray(total: 25, imagePrefix: "ImageSet3") 

最后调用animation函数

 func showAnimation() { UIView.animate(withDuration: 1, animations: { animate(imageView: self.animationView, images: self.animation1) }, completion: { (true) in // Release the Images from the Array }) } 

我想从完成块中的图像arrays释​​放图像,以降低我的内存占用,但我似乎无法得到这个工作,我已经尝试了下面的所有四个例子,但没有影响的内存足迹:

 func showAnimation() { UIView.animate(withDuration: 1, animations: { animate(imageView: self.animationView, images: self.animation1) }, completion: { (true) in self.animation1 = [] // is this correct? self.animationView.image = nil // also doesn't work self.animationView.removeFromSuperview() // also doesn't work self.animation1 = nil // also doesn't work }) } 

在完成块之后,我将animation1数组设置为[],它将删除animation(您不能再看到它),但内存占用仍然完全相同(我也尝试了其他三个选项) 。

有了上述内容,每次添加下一个animation时,内存占用就会“颠簸”,并最终导致操作系统终止应用程序

即使您更改ViewControllers,该数组仍然保存在内存中的图像

谢谢你的帮助 :)

UIImage(命名为:)将始终将图像保存在内存堆栈中,除非需要更多的内存和足够的时间来释放。

为了释放内存中的图像,你应该使用其他的构造函数:UIImage(contentsOfFile:)并将图像保存在文件夹而不是资产pipe理器。 也许数据会起作用,但我不确定。

临时/大型资源将消耗堆,你应该使用“保存”的方法,如contentsOfFile清除内存。