Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift, how to remove a UIView from memory completely?

Please considering following code:

class myManager {
    var aView: UIView!

    func createView() {
        aView = UIView()
    }

    func removeView() {
        aView = nil // anything else?
    }
}

If I create a UIView like this and later I want to remove it, is this the correct way? Anything I should be aware of?

like image 254
Joe Huang Avatar asked Jan 01 '16 11:01

Joe Huang


1 Answers

In order to have aView to be deinitialised and removed from memory you need to make it unreferenced by anything that keeps a strong reference to it. That means it should not be referenced by any part of your code, and by the UIKit view stack.

In your case it might look like this:

aView?.removeFromSuperview() // This will remove the view from view-stack
                             // (and remove a strong reference it keeps)

aView = nil                  // This will remove the reference you keep

On a side note, if you are removing the view, then you probably should not use var aView: UIView! but instead var aView: UIView?.

like image 68
0x416e746f6e Avatar answered Sep 28 '22 06:09

0x416e746f6e