Reputation: 21
I am new to Swift programming and really have high hopes from all the experts out there. While creating a simple app I ran into memory issues and my app crashed. Below are more details about my app..
My app has an image view, three images and three buttons in toolbar. All my app does right now is changes image with button press. Example if you press say button1, it will load image1, if you press button2 it would load image 2 and if you press button 3 it would load image 3.
This app crash after 1 cycle, like I can tap all the three buttons and it would work, however if I tap on any button after that it would just crash.
I am testing this on iPad mini. Works perfectly fine on simulator. Any help would be greatly appreciated. I head somewhere that UIImage (named:) can be an issue, but I don't know how to replace that with anything else in Swift.
Here is the code for it
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.
}
}
Upvotes: 1
Views: 1747
Reputation: 21
I reduced the size using png 8 format in ps and it fixed the issue for me.. Thanks all for your help :-)
Upvotes: 0
Reputation: 437552
The problem with UIImage(named: name)
is that it caches the images. As the documentation says:
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.
Thus, if you have memory problems arising from the size/number of images in the system cache, you can use UIImage(contentsOfFile: path)
rather than UIImage(named: name)
:
if let path = NSBundle.mainBundle().pathForResource("Image1", ofType: "jpg") {
TestImage.image = UIImage(contentsOfFile:path)
}
Upvotes: 3