timfi timfi - 3 months ago 23x
iOS Question

swift:ARC: how to release all references to an UIImage

I have a ios/swift project where I place a lot of UIImageViews in an scrollview. I have multiple scrollviews and I want to make sure all memory is released when I close one. So far it seems like if I add an UIImage, it gets 16 references with the following code. If I run it on any device it runs out of memory and crashes.

import UIKit

class ViewController: UIViewController

var scrollView: UIScrollView?
var backgroundView:UIImageView?
var background:UIImage?

override func viewDidLoad()
for i in 1 ..< 10000
scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: 1000, height: 1000))

if let backgroundPath = NSBundle.mainBundle().pathForResource("1", ofType: "jpg")
background = UIImage(contentsOfFile: backgroundPath)!

backgroundView = UIImageView(image: background)

backgroundView?.frame = CGRect(x: 100, y: 500, width: 500, height: 500)


scrollView!.contentSize = CGSize(width: 500, height: view.frame.height)

backgroundView = nil
scrollView = nil
background = nil

How do I get a reference count of zero to release the memory? Thanks!

Rob Rob

Only 16 references? This code creates 9,999 scroll views (each time, leaving the previous one in the view hierarchy, but abandoning your reference to it upon the next iteration), each with their own copy of 1.jpg, and each added as a subview of view. In terms of how to release the memory, you should remove any strong references you have, as well as remove any other references, such as the view hierarchy.

So, if you want to remove the references to the images, you can either reset the image property of the UIImageView, and/or remove the UIImageView (or the UIScrollView) from the view hierarchy.

Note, your attempts to set backgroundView and scrollView to nil remove your strong reference to those, but called addSubview earlier, so the view hierarchy still has a strong reference to them. If you want to get rid of everything, before setting scrollView to nil, make sure to call scrollView.removeFromSuperview() in order to remove it from the view hierarchy.