【发布时间】:2015-03-29 04:31:07
【问题描述】:
因此,我在使用 Swift 的过程中遇到了另一个障碍。我正在尝试将多个图像加载到图像库中 - 除了一件事之外,一切都很好。尽管我清除了图像,但应用程序的内存使用量仍在不断增长。基本消除所有代码后,发现这是我的图片加载脚本造成的:
func loadImageWithIndex(index: Int) {
let imageURL = promotions[index].imageURL
let url = NSURL(string: imageURL)!
let urlSession = NSURLSession.sharedSession()
let query = urlSession.downloadTaskWithURL(url, completionHandler: { location, response, error -> Void in
})
query.resume()
}
正如您所见,这段代码现在基本上什么都不做。然而,每次我调用它时,我的应用程序内存使用量都会增加。如果我注释掉查询,内存使用不会改变。
我已经阅读了几个类似的问题,但它们都涉及使用委托。好吧,在这种情况下,没有委托,但存在内存问题。有谁知道如何消除它以及是什么原因造成的?
编辑:这是一个完整的测试类。似乎只有在可以加载图像时内存才会增长,就像指向图像的指针将永远保存在内存中一样。当找不到图像时,什么也没有发生,内存使用率保持在低水平。也许一些提示如何清理这些指针?
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
//memory usage: approx. 23MB with 1 load according to the debug navigator
//loadImage()
//memory usage approx 130MB with the cycle below according to the debug navigator
for i in 1...50 {
loadImage()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadImage() {
let imageURL = "http://mama-beach.com/mama2/wp-content/uploads/2013/07/photodune-4088822-beauty-beach-and-limestone-rocks-l.jpg" //random image from the internet
let url = NSURL(string: imageURL)!
let urlSession = NSURLSession.sharedSession()
let query = urlSession.downloadTaskWithURL(url, completionHandler: { location, response, error -> Void in
//there is nothing in here
})
query.resume()
}
}
对不起,我还不知道如何使用分析器(在整个 iOS 爵士乐中非常菜鸟),至少我会附上上面代码生成的分析器的屏幕截图:
【问题讨论】:
-
您在
completionHandler中使用什么代码?听起来像是一个保留周期正在发生。你可以使用工具来分析内存分配和磁盘的读/写吗? -
@LouisTur 问题已更新。
-
将您的代码嵌入到 auroreleasepool 块中。我没有看到仪器报告的任何泄漏。
-
您在 1.2MB+ 的图像文件上调用此
loadImage方法 50 次,使用下载任务将结果保存到磁盘。有可能这就是你记忆力猛增的原因。如果只调用一次,它的行为是否相同? -
@LouisTur 我在这里感到困惑吗?内存信息是可用的 RAM 内存,不是吗?这里的问题不是尖峰,而是它实际上从未下降。我假设如果不访问文件数据,它就会被垃圾收集。但似乎并非如此。如果我调用一次这个方法,当然它只是在内存中产生了一点点差异,没有什么特别的。
标签: ios swift memory memory-leaks nsurlsession