在Swift中,如何完全从内存中删除UIView?

Joe*_*ang 4 uiview swift swift2

请考虑以下代码:

class myManager {
    var aView: UIView!

    func createView() {
        aView = UIView()
    }

    func removeView() {
        aView = nil // anything else?
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我创建UIView这样的,后来我想删除它,这是正确的方法吗?我应该注意什么?

cou*_*elk 10

为了必须aView将其初始化并从内存中删除,您需要使任何对其有强烈引用的内容不引用它.这意味着它不应该被代码的任何部分 UIKit视图堆栈引用.

在您的情况下,它可能看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

另外,如果您要删除视图,那么您可能不应该使用var aView: UIView!而是使用var aView: UIView?.