简体   繁体   English

Swift 2.2内存管理

[英]Swift 2.2 memory management

So I have an UIView that contains an UIImageView with a fairly large image (say 1600x1600). 所以我有一个包含UIImageView的UIView,它有一个相当大的图像(比如1600x1600)。 When I load it I can see on Xcode that the memory goes up as expected but still manageable. 当我加载它时,我可以在Xcode上看到内存按预期上升但仍然可管理。

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: 现在,如果我myView.removeFromSuperview() ,内存不会下降,如果我一直添加和删除其他图像的视图,例如:

  1. set image 设置图像
  2. add it to the view 将其添加到视图中
  3. remove image from superview 从superview中删除图像
  4. set another image 设置另一个图像
  5. add it to the same view 将其添加到同一视图中
  6. back to 3 and continue looping 回到3并继续循环

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? 当我从superview中删除图像时,不应该释放内存吗?

With Swift, using ARC (Automatic Reference Counting), it's not possible to manually free up memory. 使用Swift,使用ARC(自动引用计数),无法手动释放内存。 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 . 有一篇很好的NSHipster文章讨论了在这个链接中调整Swift图像大小的不同技巧。

// 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. UIKit提供了许多用于图像大小调整的高级API,它们直接影响图像在屏幕上的显示方式,因此也适用于主UI线程。

To conclude, optimize the way you represent this big image on the screen to optimize the required amount of memory. 最后,优化在屏幕上表示此大图像的方式,以优化所需的内存量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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