目标:
这是我的代码:
mainImageView.image = UIImage(named:"FirstImage.png") // load first image, no issues
然后,如果您以编程方式将第二个图像加载到同一UIImage中,则会导致设备发出内存不足警告,并且iOS导致应用程序崩溃:
mainImageView.image = UIImage(named:"SecondImage.png") // load second image
最佳答案
在阅读了关于SO和其他文章的许多答案(见下文)之后,将多个图像加载到动画数组中时管理内存的最佳方法是使用contentsOfFile: imageName
而不是UIImage(named:"FirstImage.png")
在这里查看文章:
http://www.alexcurylo.com/2009/01/13/imagenamed-is-evil/
其次,Apple声明以下内容:
If a matching image object is not already in the cache, this method locates and loads the image data from disk or from an available asset catalog, and then returns the resulting object. The system may purge cached image data at any time to free up memory. Purging occurs only for images that are in the cache but are not currently being used. In iOS 9 and later, this method is thread safe. Special Considerations 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.
https://developer.apple.com/documentation/uikit/uiimage/1624146-init
最后,在收到内存警告后,您还可以创建以下功能:
func applicationDidReceiveMemoryWarning(application: UIApplication) {
NSURLCache.sharedURLCache().removeAllCachedResponses()
}
希望这对其他人有帮助:)
关于ios - 加载图像时iOS应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47724233/