我正在爲將返回對象列表的函數創建一個完成處理程序。當它第一次返回值時,它運行良好。但是,當任何更改發生在firebase數據庫中,並且再次觀察被調用時,數組大小會增加一倍。爲什麼它會翻倍?完成處理程序在Swift中的Firebase觀察者
func getStadiums(complition: @escaping ([Stadium]) -> Void){
var stadiums: [Stadium] = []
let stadiumRef = Database.database().reference().child("Stadium")
stadiumRef.observe(.value, with: { (snapshot) in
for snap in snapshot.children {
guard let stadiumSnap = snap as? DataSnapshot else {
print("Something wrong with Firebase DataSnapshot")
complition(stadiums)
return
}
let stadium = Stadium(snap: stadiumSnap)
stadiums.append(stadium)
}
complition(stadiums)
})
}
,並呼籲像這樣
getStadiums(){ stadiums
print(stadiums.count) // count gets doubled up after every observe call
}
Thanks @Jen :)它真的有效 –