Skip to main content
 首页 » 操作系统

ios之如何阻止我的 swift 应用程序崩溃

2024年01月01日54mate10pro

我是 Swift 编程的新手,我真的对那里的所有专家寄予厚望。在创建一个简单的应用程序时,我遇到了内存问题,我的应用程序崩溃了。以下是有关我的应用程序的更多详细信息..

我的应用程序在工具栏中有一个 ImageView 、三个图像和三个按钮。我的应用程序现在所做的就是通过按下按钮更改图像。例如,如果您按下按钮 1,它将加载图像 1,如果您按下按钮 2,它将加载图像 2,如果您按下按钮 3,它将加载图像 3。

这个应用程序在 1 个循环后崩溃,就像我可以点击所有三个按钮并且它会工作,但是如果我在那之后点击任何按钮它就会崩溃。

我正在 iPad mini 上对此进行测试。在模拟器上工作得很好。任何帮助将不胜感激。我前往 UIImage(名为 :) 可能是个问题的地方,但我不知道如何用 Swift 中的其他任何东西替换它。

这是它的代码

import UIKit 
 
class ViewController: UIViewController 
{ 
   @IBOutlet weak var TestImage: UIImageView! 
 
   @IBAction func Button1(sender: AnyObject) 
   { 
      TestImage.image = UIImage (named: "Image1.jpg") 
 
   } 
 
   @IBAction func Button2(sender: AnyObject) 
   { 
      TestImage.image = UIImage (named: "Image2.jpg") 
   } 
 
   @IBAction func Button3(sender: AnyObject) 
   { 
      TestImage.image = UIImage (named: "Image1.jpg") 
   } 
 
   override func viewDidLoad() 
   { 
      super.viewDidLoad() 
      // Do any additional setup after loading the view, typically from a nib. 
   } 
 
   override func didReceiveMemoryWarning() 
   { 
      super.didReceiveMemoryWarning() 
      // Dispose of any resources that can be recreated. 
   } 
} 

请您参考如下方法:

UIImage(named: name) 的问题在于它缓存了图像。作为the documentation说:

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.

因此,如果系统缓存中的图像大小/数量导致内存问题,您可以使用 UIImage(contentsOfFile: path) 而不是 UIImage(named: name) :

if let path = NSBundle.mainBundle().pathForResource("Image1", ofType: "jpg") { 
    TestImage.image = UIImage(contentsOfFile:path) 
}