为什么在移除观察者后第一次初始化我的UIView de,但之后它是?

时间:2017-03-04 19:15:16

标签: ios swift firebase uiview firebase-realtime-database

我有一个UIView,它正在添加到父ViewController,它有一个Firebase观察器,当我从父控制器中删除UIView时,我将删除它。但是第一次删除UIView时,deinit()不会被调用,但是,如果我再次添加并删除,则每次调用deinit()。我无法弄明白为什么,任何想法?

与观察员联系:

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
    }
}

1 个答案:

答案 0 :(得分:0)

因此,当您第一次点击时,在添加git config --local --list

的第一次点击时,这会被称为@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!) 现在,当您单击按钮时,它将按您的意愿执行。