即使有一个值,在展开一个 Optional 值时也发现 nil

问题描述

我正在使用 segue 将数据从一个控制器传递到另一个控制器。奇怪的是,第二个视图控制器能够检测到代码的一部分中的数据值,并在另一部分中抛出“Unexpectedly found nil while unwrapping an Optional value”错误。有人可以帮忙吗?

视图控制器 1:将数据传递给视图控制器 2

override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
    if segue.identifier == "showMsg" {
        
       let nav = segue.destination as! UINavigationController
       let VC = nav.topViewController as! MessagesViewController
                if let ref = ref {
                        DatabaseConnect.fetchTransactionUser(ref: ref,completion: { (user) in
                            if let user = user {
                                VC.userId = "Data passed"

                            }
                        })
                }
    }
}

视图控制器 2:从视图控制器 1 检索数据

  var userId:String?
  func fetchFeed() {
  
  let message = Database.database().reference().child("allmessages").child(currentUser).child(userId!) //ERROR HERE!
        message.observe(.value,with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                let postId = value?["postId"] as? String ?? ""
        })
  }

  //meanwhile,later in the file,this action is working below for some reason
    @IBAction func postCommentAction(_ sender: Any) {
    var commentText = ""
    
    if let text = textFieldLabel.text {
        
       commentText = text
        
    }
    
    if commentText != "" {
        
        let currentUser = Auth.auth().currentUser!.uid
                    
        let messageIdExist = Database.database().reference().child("allmessages").child(currentUser).child(userId!) //THIS WORKS!
                    
                    messageIdExist.observeSingleEvent(of: .value,with: { (snapshot) in
                         
                           })

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)