我有一个 UIView 添加到 UIViewController 中,并且通常测试去初始化以确保我做的事情是正确的。但是,当我没有将 viewController 中的变量设置为 nil 并仅使用 .removeFromSuperView() 时,UIView 中的 deinit() 方法将不会被调用,直到我再次添加 UIView 然后调用它。但如果我使用removeFromSuperView()并将变量设置为nil,那么 deinit() 会立即被调用。这是为什么?
这是 UIView() 类:
class TestView: UIView {
override init(frame: CGRect) {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
print("init is happneing")
}
deinit {
print("de init is happneing")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
这是父 ViewController :
class MyViewController: UIViewController {
var tstview : TestView?
//adding the UIView by tapping on a button
@IBAction func addView(_ sender: UIButton) {
let test = TestView()
tstview = test
tstview?.frame = CGRect(x: 50, y: 60, width: self.view.frame.width-100, height: self.view.frame.height-200)
tstview?.backgroundColor = UIColor.white
self.view.addSubview(tstview!)
}
override func viewDidLoad() {
super.viewDidLoad()
}
//removing UIView by touching elsewhere
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
tstview?.removeFromSuperview()
// tstview = nil
}
}
deinit
当没有人引用该对象时调用。如果你不设置tstview
to nil
,您的 MyViewController 仍在引用它,因此deinit
不会被调用。你打电话时addView
, 该声明tstview = test
最后删除对旧视图的最后一个引用,从而触发析构器。
您可以阅读有关反初始化概念的更多信息斯威夫特文档 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Deinitialization.html.
如果您希望在视图分离后立即收到通知,覆盖willMove(toSuperview:) https://developer.apple.com/reference/uikit/uiview/1622629-willmove反而。
class TestView: UIView {
...
override func willMove(toSuperview newSuperview: UIView?) {
if newSuperview == nil {
print("removed from parent")
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)