gpt4 book ai didi

ios - 为什么我的 UIView de 在删除观察者后第一次没有初始化,但之后却初始化了?

转载 作者:行者123 更新时间:2023-11-30 12:38:15 24 4
gpt4 key购买 nike

我有一个 UIView 添加到父 ViewController 中,并且它有一个 Firebase 观察者,当从父 Controller 中删除 UIView 时,我将删除该观察者。但是第一次删除 UIView 时, deinit() 将不会被调用,但之后,如果我再次添加它并删除,则每次都会调用 deinit() 。我不明白为什么,有什么想法吗?

带有观察者的 UIView:

class TestView: UIView  { 
var ref = FIRDatabase.database().reference()
var hndlI : FIRDatabaseHandle?

hndlI = ref.child(node).observe(.childAdded , with: { (snap) in
...
}

func rmvObsr() { //this method is called in parent controller before removing the UIView to remove the observer
ref.child(node).removeAllObservers()
}

deinit {
print("de initing ")
}
}

这里是 paren UIViewController,它通过点击按钮来添加 UIView:

class ParentController: UIViewController {
weak var tstVw: TestView?

//adding UIView
@IBAction func seeSocialMedia(_ sender: UIButton) {

let view = TestView()
tstVw = view

tstVw?.frame = CGRect(x: 50, y: 60, width: self.view.frame.width-100, height: self.view.frame.height-200)

self.view.addSubview(tstVw!)
}


//removing UIView by tapping elsewhere
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
tstVw?.rmvObsr() //removing observer
tstVw?.removeFromSuperview()
tstVw = nil
}
}

最佳答案

因此,当您第一次单击时,第一次单击时将调用 @IBAction func seeSocialMedia(_ sender: UIButton) ,添加 self.view.addSubview(tstVw!)

然后在第二次单击时将其删除(如果我正确地阅读了代码)。这就是为什么它会在第二次单击时被删除。我搬家了

let view = TestView()
tstVw = view

tstVw?.frame = CGRect(x: 50, y: 60, width: self.view.frame.width-100, height: self.view.frame.height-200)

self.view.addSubview(tstVw!)

现在,当您单击按钮时,它会按照您想要的方式执行viewDidLoad

关于ios - 为什么我的 UIView de 在删除观察者后第一次没有初始化,但之后却初始化了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42600213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com