Reputation: 2352
So I have an UIView that contains an UIImageView with a fairly large image (say 1600x1600). When I load it I can see on Xcode that the memory goes up as expected but still manageable.
Now if I myView.removeFromSuperview()
the memory doesn't go down and if I keep adding and removing the view with the other images one at a time, something like:
After every iteration I see that the memory keeps increasing until eventually I run out of memory, receive a memory warning and crash.
Is this expected? shouldn't the memory be released when I remove the image from superview?
Upvotes: 4
Views: 137
Reputation: 163
With Swift, using ARC (Automatic Reference Counting), it's not possible to manually free up memory. Memory Management is strictly delegated to the OS and if you want to improve memory performances on your app the only way is to improve the code itself.
If you're working with such a big image chances are that it's possible to scale down the resolution of the image itself without loosing any functionality on the app. When displaying this image you could also implement caching or 'real time' compression that's executed on the main thread avoiding to use precious memory to represent pixels. There's a good NSHipster article talking about different techniques to resize images in Swift at this link.
// Basic usage of UIGraphicsGetImageFromCurrentImageContext()
let yourScaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIKit offers a number of high level APIs for image resizing that act directly on the way images are displayed on the screen, and consequently on the main UI thread.
To conclude, optimize the way you represent this big image on the screen to optimize the required amount of memory.
Upvotes: 3