RanLearns
RanLearns

Reputation: 4176

How to clear memory after UIImageView.animationImages?

I've created a new Xcode project that has only the following:

When the button is pressed and the animation plays, the memory usage increases by 150-200MB, depending on the number of images in the image array. Then the memory usage remains at that level.

Setting imageView.animationImages = nil doesn't clear the memory. How could I go about clearing that memory?

Any suggestions would be helpful. Thanks!

Upvotes: 3

Views: 2443

Answers (1)

Stephan Schlecht
Stephan Schlecht

Reputation: 27096

1. Don't implicitely cache images

I guess you are using UIImage(named:)?

This method caches the images, see: https://developer.apple.com/documentation/uikit/uiimage/1624146-init

Apple recommends:

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.

So using 'UIImage(contentsOfFile: String)' should solve your problem. Due to the documentation you need to supply a path to the image, the image name is not sufficient, see here:

https://developer.apple.com/documentation/uikit/uiimage/1624123-imagewithcontentsoffile

There it is also mentioned:

This method does not cache the image object.

2. Don't hold references to the images

When you are loading the images into a local array make sure to empty it.

self.imageArray = []

3. Set imageView.animationImages to an empty array

self.imageArray = []
self.imageView.animationImages = self.imageArray

Quick verification of the allocations in Instruments:

allocations in Instruments

As you can see the memory is reclaimed. All good.

Upvotes: 6

Related Questions