简体   繁体   English

发现 nil 时崩溃,同时隐式展开非 nil 的可选值

[英]Crash when found nil while implicitly unwrapping an Optional value that is not nil

I'm developing an iOS database app using Firebase.我正在使用 Firebase 开发一个 iOS 数据库应用程序。 After Authentication (which performs successfully), the userUID gets passed from my LoginViewController to my HomeViewController.在身份验证(成功执行)之后,userUID 从我的 LoginViewController 传递到我的 HomeViewController。 Then, in my HomeViewController, I use the user's UID to get the rest of the user's info from the Cloud Firestore associated with that UID.然后,在我的 HomeViewController 中,我使用用户的 UID 从与该 UID 关联的 Cloud Firestore 中获取用户信息的 rest。 After retrieving it, I want to show the first and last name in a label.检索后,我想在 label 中显示名字和姓氏。 I'm certain that the retrieval of the info is successful and that I do have two strings (firstName and lastName).我确定信息的检索是成功的,并且我确实有两个字符串(名字和姓氏)。 When I print them in the console I get precisely what I want.当我在控制台中打印它们时,我得到的正是我想要的。 But I don't know why, when I try to show such strings in a label, I get the following error:但我不知道为什么,当我尝试在 label 中显示此类字符串时,出现以下错误:

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file /Users/fafa/Documents/Advisory Program/Advisory Program/HomeViewController.swift, line 41致命错误:在隐式展开可选值时意外发现 nil:文件 /Users/fafa/Documents/Advisory Program/Advisory Program/HomeViewController.swift,第 41 行

I've tried several things, but I can't seem to fix this.我已经尝试了几件事,但我似乎无法解决这个问题。 Here's part of my code:这是我的代码的一部分:

LoginViewController.swift LoginViewController.swift

@IBAction func loginTapped(_ sender: Any) {
    
    let error = validateFields()
    
    if error != nil {
        
        showErrorMessage(error!)
        
    } else {
        
        let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        
        Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
            
            if error != nil {
                
                self.showErrorMessage(error!.localizedDescription)
            
            } else {
                
                let homeViewController = self.storyboard?.instantiateViewController(withIdentifier: "HomeVC") as? HomeViewController
                self.navigationController?.pushViewController(homeViewController!, animated: true)
                
                homeViewController!.userUID = result!.user.uid
                
            }
        }
    }
}

HomeViewController.swift HomeViewController.swift

override func viewDidLoad() {
    super.viewDidLoad()
    
    let db = Firestore.firestore()
    db.collection("teachers").whereField("uid", isEqualTo: userUID).getDocuments { (snapshot, error) in
    
        if let error = error {
                    
            print("Error getting documents: \(error)")
                    
        } else {

            for document in snapshot!.documents {

                // Error gets printed in the following line
                TeacherHeaderCollectionReusableView().teacherNameLabel.text = "\(document.get("firstName") ?? "default value") \(document.get("lastName") ?? "default value")" 

                print("\(document.documentID) => \(document.data())")
            }
        }
    }
}

TeacherHeaderCollectionReusableView.swift TeacherHeaderCollectionReusableView.swift

class TeacherHeaderCollectionReusableView: UICollectionReusableView {

    @IBOutlet weak var teacherHeaderView: UIView!
    @IBOutlet weak var teacherPhoto: UIImageView!
    @IBOutlet weak var teacherNameLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        
        //teacherHeaderView.backgroundColor = UIColor.init(red: 140/255, green: 3/255, blue: 3/255, alpha: 1)
        let blurEffect = UIBlurEffect(style: .dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = teacherHeaderView.bounds
        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        teacherHeaderView.insertSubview(blurEffectView, at: 0)
        teacherHeaderView.layer.cornerRadius = 10.0
        teacherHeaderView.layer.masksToBounds = true
    
        teacherPhoto.layer.cornerRadius =  teacherPhoto.frame.width/2.0
        teacherPhoto.clipsToBounds = true
        teacherNameLabel.textColor = .white
    }

    func configure(image:UIImage, name:String) {
        teacherPhoto.image = image
        teacherNameLabel.text = name
    }

    static func nib() -> UINib {
        return UINib(nibName: "TeacherHeaderCollectionReusableView", bundle: nil)
    }

}

Here the teacherNameLabel of type UILabel is nil .这里UILabel类型的teacherNameLabelnil You have to initialize the TeacherHeaderCollectionReusableView from xib to avoid the crash.您必须从 xib 初始化TeacherHeaderCollectionReusableView以避免崩溃。 In this line: TeacherHeaderCollectionReusableView().teacherNameLabel.text you're trying to create a new instance of TeacherHeaderCollectionReusableView by using an empty initializer.在这一行中: TeacherHeaderCollectionReusableView().teacherNameLabel.text您正在尝试使用空初始化程序创建TeacherHeaderCollectionReusableView的新实例。 Using an empty initializer would not load the subviews that you've created in the interface builder.使用空的初始化程序不会加载您在界面构建器中创建的子视图。 Here's an example of how you initialize the TeacherHeaderCollectionReusableView properly.这是一个如何正确初始化TeacherHeaderCollectionReusableView的示例。

let nib = UINib(nibName: "TeacherHeaderCollectionReusableView", bundle: nil)
let teacherHeaderCollectionReusableView = nib.instantiate(withOwner: nil, options: nil)[0] as? TeacherHeaderCollectionReusableView
teacherHeaderCollectionReusableView?.teacherNameLabel.text = "..."

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM