ios - 加载图像时iOS应用程序崩溃

标签 ios swift crash imageview

目标:

  • 从Assets.xcassets文件夹以编程方式将第一个图像(约94kb)加载到主 Storyboard上的ImageView中(请参见下面的代码)-完美的
  • 然后,当您将第二张图像(相同大小)加载到原始UIImage中时,它将导致iOS应用程序崩溃。

  • 这是我的代码:

    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/

    相关文章:

    ios - override init 和 required init 之间的区别? - swift

    ios - App ios 关闭时 GCM 不发送通知

    ios - 如何在 Swift 中自动移动到下一个 UITextField

    ios - Xcode 连续崩溃给定线程 1 exc_bad_access (code=2 address=0x8)

    iOS 从 UIWebView 移除阴影

    ios - sqlite 加入查询 iPad

    iphone - 为什么在将 Float 转换为 CGFloat 时 Xcode 给我一个警告 "Cannot convert value of type ' CGFloat' to expected argument type 'UnsafeMutablePointer"?

    ios - 如何在 Swift 中从其 ViewController 获取 UIView 子类实例

    opencv - 使用外部摄像头时,Opencv应用程序崩溃

    c# - 变量未声明或从未分配?和数据读取器不工作?