简体   繁体   中英

Swift Memory Management

I am developing an app in Swift and I am coming from non-arc Objective-C background. I ran into memory issues. So, I implemented deinit in my ViewControllers. None of them got called. Some code example:

@objc protocol ServerDelegate {
    @objc optional func onUpdateComplete ()
}

var delegate_ : ServerDelegate?

I googled around and found that all my delegates were set to strong references. So, I made them weak references like:

@objc protocol ServerDelegate : class {
    @objc optional func onUpdateComplete ()
}

weak var delegate_ : ServerDelegate?

and now deinit is called for each ViewController.

However, when I see memory it does get freed up when I pop a View Controller from Navigation Controller. For example, In the very first scene I had 10 MB of memory allocated, I pushed a view controller, memory increased to 15 MB. Now when I pop it, deinit is called but this extra 5 MB is not freed. But if I push it again. Memory does not increase to 20 MB. It stays at 15 MB. Why is this happening? Is this normal? Are the images being cached and not released? Can I manually release them when I pop the View Controller? Thanks.

There is a system cache for images per the documentation of UIImage.init(named:) ; you cannot manually flush it but Apple's design intention is that you wouldn't ever get any benefit from doing so if you could — like all NSCache -type caches it'll automatically flush itself should memory ever become scarce. So in the meantime all a flush would achieve would be fewer cache hits and expenditure of the processor cycles required for the flush.

The documentation advises use of imageWithContentsOfFile: if you want to avoid the cache but if you're loading or being loaded from a XIB or Storyboard then you don't have sufficient direct control to assert influence.

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