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

7
请考虑以下代码:
class myManager {
    var aView: UIView!

    func createView() {
        aView = UIView()
    }

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

如果我像这样创建一个 UIView,然后稍后想要将其删除,这是正确的方法吗?有什么需要注意的吗?

1
aView.removeFromSuperview() - Adam
2个回答

15
为了使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!


-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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接