简体   繁体   中英

Swift 2.2 memory management

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:

  1. set image
  2. add it to the view
  3. remove image from superview
  4. set another image
  5. add it to the same view
  6. back to 3 and continue looping

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM