In Swift, how to remove a UIView from memory compl

2019-02-24 10:11发布

问题:

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?

回答1:

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?.



回答2:

class A {
    deinit {
        print("A deinit") // (2)
    }
}

class B {
    var a: A! = A()
    func killA() {
        a = nil
    }
}

let b = B()
if b.a == nil {
    print("b.a is nil")
} else {
    print(b.a)  // (1)
}
b.killA()
if b.a == nil {
    print("b.a is nil") // (3)
} else {
    print(b.a)
}
/*
A
A deinit
b.a is nil
*/

// warning !!!!!
print(b.a) // now produce fatal error: unexpectedly found nil while unwrapping an Optional value
// you always need to check if the value of b.a is nil before use it