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

标签 ios swift firebase uiview firebase-realtime-database

我有一个 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/

相关文章:

arrays - 搜索 UITableView 的多个部分,数组结构数组

ios - Flutter 构建失败 'UserAgent.h' 找不到文件

ios - -[UIImage长度] : unrecognized selector sent to instance error with a NSMutableArray with Images

ios - SCNAnimationPlayer 开始播放手势动画

objective-c - isKindOfClass 没有按预期工作

ios - 使用开关更改 UITabBar 样式

ios - iOS模拟器没有当前位置吗

javascript - Firebase 函数问题以及 .add() 与 .doc().set() 之间的区别

ios - 在具有多个 Android 应用程序和一个 iOS 应用程序的 Firebase 中注册新的 bundle ID 时出现错误

angular - PayPal Rest API、firebase 函数和 Angular 6 的 CORS 错误