Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImageView instances of NSPathStore2 leaked

I am loading png images from the Document directory into an UIImageView. When using the xcode Debug memory graph it comes up with Memory issues: instances of NSPathStore2 leaked instances of NSPathStore2 leaked

I have heard that the instrument's leak tool can report false leaks.

The memory seems to not go up: enter image description here

The problem seems to be in UIImage, see Instruments Leak report: enter image description here

Here is the code that produces the images:

           try FileManager.default.copyfileToUserDocumentDirectory(forResource: "smiley", ofType: ".png")

            var fullPathString = ""
            if let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                                .userDomainMask,
                                                                true).first {
                let fileName = "smiley.png"
                let fullDestPath = URL(fileURLWithPath: docDir).appendingPathComponent(fileName)
                fullPathString = fullDestPath.path
            }

            mainStackView.addArrangedSubview(UIImageView(image: UIImage(contentsOfFile: fullPathString)))
            mainStackView.addArrangedSubview(UIImageView(image: UIImage(contentsOfFile: fullPathString)))


The working project producing this problem can be found here: UIImageViewNSPathStore2leaked

Is there a way to change the code so that these leaks go away, or is this one of those false reports?

like image 930
Matthias Avatar asked May 16 '20 05:05

Matthias


1 Answers

I have the issue too.

Reproduce

Just create clean new project to reproduce the issue.

  1. Drag image.png to project, make sure it in Copy Bundle Resources.
  2. Write these two lines in viewDidLoad.
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let path = Bundle.main.path(forResource: "image", ofType: "png")!
        let _ = UIImage(contentsOfFile: path)
    }
}
  1. Build and Run it.
  2. Click Debug Memory Graph when viewController appeared.
  3. You can see leak issues.

Not sure is it a bug of init(contentsOfFile:)?

Solution

I changed the API init(data:) instead of init(contentsOfFile:) to solve the problem.

let url = Bundle.main.url(forResource: "image", withExtension: "png")!
let imageData = try! Data(contentsOf: url)
let _ = UIImage(data: imageData)

Using Xcode 11.5/11.3.1 and Swift 5

like image 94
digdoritos Avatar answered Oct 05 '22 22:10

digdoritos