How to manage my images to avoid ImageIO_PNG_Data overflow?

Hi,


I'm trying to build an app where you have a catalog of images and a canvas to drag and drop copies of the images in that catalog in different positions (like drag-and-drop animal images over a forest background). Potentially I can drop N amount of the same image over that canvas.

My problem is that I get 'terminated due to out of memory' error because ImageIO_PNG_Data just grows out of proportion.


The way I'm creating the background of the canvas is as follows:

let image = UIImage(named: fileName1x)
image!.imageAsset!.register(UIImage(named: fileName2x)!, with: scale2x)
image!.imageAsset!.register(UIImage(named: fileName3x)!, with: scale3x)


The way I'm creating each image that the user drag-and-drop from the catalog is as follows:

        // They are animated so I create each frame as a UIImage
        let framesNames = recurso.accion?.getFrames()
        var frames:[UIImage] = []
        for frameName in framesNames! {
                    let frame = UIImage(named: frameName) // should i use contentsOfFile?
                    if (frame != nil) {
                        frames.append(frame!)
                    }
        }
        // I create the ImageView with all the frames needed for the animation
        let imageView = UIImageView(frame: graphicResourceView.bounds)
        imageView.contentMode = UIViewContentMode.scaleAspectFit
        imageView.animationImages = frames
        imageView.animationDuration = animationDuration
        imageView.startAnimating()


I read recommendations of creating images using contentsOfFile to avoid this problem... the thing is that according to Apple Documentation, "you should not use them to load the same image repeatedly" and I'm doing exactly that :s


Does anyone have any recommendation or idea as to how I can solve this image memory problem? Is there a way to purge that cached memory? maybe if I remove all those UIImageView from their superview before the ViewController Disappears?


Thanks

Replies

Bumping this, anyone?

If you are using an asset catalog, why are you registering the images by scale in code? Typically, you add the images by scale in the asset catalog, then just get the image with UIImage(named: fileName).

Hi,


I'm not, those images are either on a folder within my project or downloaded (by the user) onto the app directory 🙂 that's why I'm creating it manually.

If you are reusing the images, you should try using imageNamed: in your for loop. As far as I know, using imageNamed: for the same image N times only loads the image into the memory cache once.