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

时间:2016-01-01 11:36:10

标签: swift uiview swift2

请考虑以下代码:

class myManager {
    var aView: UIView!

    func createView() {
        aView = UIView()
    }

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

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

2 个答案:

答案 0 :(得分:9)

为了让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

另外,如果要移除视图,则可能不应使用var aView: UIView!,而应使用var aView: UIView?

答案 1 :(得分:0)

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
相关问题