关于 ios:Crash when found nil while implicitly unwrapping an Optional value that is not nil

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

我正在使用 Firebase 开发一个 iOS 数据库应用。在身份验证(成功执行)之后,userUID 从我的 LoginViewController 传递到我的 HomeViewController。然后,在我的 HomeViewController 中,我使用用户的 UID 从与该 UID 关联的 Cloud Firestore 获取用户的其余信息。检索后,我想在标签中显示名字和姓氏。我确定信息检索成功并且我确实有两个字符串(名字和姓氏)。当我在控制台中打印它们时,我得到的正是我想要的。但我不知道为什么,当我尝试在标签中显示此类字符串时,出现以下错误:

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file /Users/fafa/Documents/Advisory Program/Advisory Program/HomeViewController.swift, line 41

我已经尝试了几件事,但我似乎无法解决这个问题。这是我的代码的一部分:

LoginViewController.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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)
    }

}


这里 UILabel 类型的 teacherNameLabelnil。您必须从 xib 初始化 TeacherHeaderCollectionReusableView 以避免崩溃。在这一行中: TeacherHeaderCollectionReusableView().teacherNameLabel.text 您正在尝试使用空的初始值设定项来创建 TeacherHeaderCollectionReusableView 的新实例。使用空的初始化程序不会加载您在界面构建器中创建的子视图。这是一个如何正确初始化 TeacherHeaderCollectionReusableView 的示例。

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