如何阻止我的快速应用程序崩溃

时间:2015-01-03 10:16:52

标签: ios image ipad swift memory

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

我的应用在工具栏中有一个图像视图,三个图像和三个按钮。我现在所有的应用程序都是按下按钮更改图像。例如,如果按下说按钮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.
   }
}

2 个答案:

答案 0 :(得分:3)

UIImage(named: name)的问题在于它会缓存图像。正如the documentation所说:

  

如果您的图像文件只显示一次,并希望确保它不会添加到系统的缓存中,则应使用imageWithContentsOfFile:创建图像。这会将您的一次性图像保留在系统图像缓存之外,从而可能会改善应用程序的内存使用特性。

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

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

答案 1 :(得分:0)

我在ps中使用png 8格式减小了大小,它解决了我的问题..感谢大家的帮助: - )