我还是个菜鸟,要弄清楚这个错误我有点困难。
我正在使用一个非常基本的健身记录应用程序,该应用程序由NavigationStack内部的两个TableViewController组成。我将Firebase / Firestore用作后端,并且为每个viewController设置了snapShotListeners,以用于添加或删除新数据的时间。
我遇到的错误很难解释,但我会尽力而为...
firstTableViewController
中创建了两个新文档,分别名为“ A”和“ B”,然后在每个文档中,我分别在secondViewController
中创建了两个文档,分别命名为“ C”和“ D”。firstTableViewController
中删除文档“ A”和“ B”,这也会自动删除两对文档“ C”和“ D”。所有这些更改都已在Firestore后端进行了观察和反映,因此没有问题,一切都按预期的方式运行。TableViewControllers
。因此,现在我尝试通过重新创建我之前创建的两个文件来执行与我完全相同的操作,即使用完全相同的名称“ A”和“ B”,并且我还尝试重新创建文档“ C” ”和“ D”分别位于“ A”和“ B”中。但是这一次,当我尝试在文档“ B”中重新创建文档“ D”时,由于某种原因,我的diff.type == .removed
在我的snapShotListener
上的secondViewController
中被执行了,我得到了Unexpectedly found nil while unwrapping an Optional value
代码... 我不知道为什么会这样并且伤了我的头。任何帮助或指导将不胜感激。再说一次,我对此还很陌生,所以我的调试技能还不够好。我很乐意包含代码,但是我不确定应该显示多少代码...请告诉我。
谢谢你!
编辑:
如果我的SecondViewController
中只有两个文档(“ C”和“ D”),则当我输入该VC时,我的diff.type == .added
会执行4次而不是2次。它会显示“ Document”即使该集合中只有2个文档,也添加了“ 4次”。这是代码...
//MARK: - Load the Data
func loadExercises() {
feedback = self.exerciseCollection!.whereField("Workout", isEqualTo: selectedWorkout!.workout).order(by: "Timestamp", descending: false).addSnapshotListener({ (querySnapshot, err) in
let group = DispatchGroup()
guard let snapshot = querySnapshot else {return}
snapshot.documentChanges.forEach { diff in
if (diff.type == .added) {
self.exerciseArray.removeAll()
group.enter()
for document in querySnapshot!.documents {
let workoutData = document.data()
let exercise = workoutData["Exercise"] as! String
let newExercise = Exercise(Day: self.selectedWorkout!.day, Workout: self.selectedWorkout!.workout, Exercise: exercise, Key: document.reference)
self.exerciseArray.append(newExercise)
print("Document Added")
}
group.leave()
group.notify(queue: .main){
self.tableView.reloadData()
}
}
if (diff.type == .removed) {
print("Document Removed")
self.tableView.deleteRows(at: [self.indexToRemove!], with: .automatic)
}
}
}
)}