Search code examples
iosswiftmemoryanimated-gif

Loading GIFs in iOS consumes too much memory


I've been testing around a lot of open-source animated-gif libraries to load GIF files into our Swift project.

Most of them claim to be high-performance libraries, however, whenever I load an animated gif my application uses around 8MB of memory.

The problem is that this dedicated memory space seems to never be released. We can see it growing linearly:

enter image description here

And it makes me wonder if I'm doing the right thing here. Is this behavior correct, or is it potentially bad for the user?


Solution

  • you would need to remove the Gif images manually for them to get cleared from the memory.

    Example: gifViwer can be your Gif Viewer in this example

    self.gifViewer.removeFromSuperview()
    self.gifViewer = nil
    

    if you had to assign a delegate then you can also add

    self.gifViewer.Delegate = nil
    

    Note: you need to run this when the viewControler is being completely unloaded as the app will start looking for gifViewer in the view while it has been removed. if you need to clear the gif image from the memory without unloading the view then I suggest to use the steps above and then adding the view to the superView programatically. this is not going to work with the interface designer and IBOutlets

    let gifViewer = yourGifViewerClass(frame: CGRect(x: 20, y: 20, width: self.view / 2, height: self.view / 2))
        //  setup your gifViewer