![](/img/trans.png)
[英]Load Firebase date into UITableView by observeSingleEventOfType and attach ChildAdded Observer
[英]Firebase .childAdded observer duplicating children
我試圖讓我的程序將一個孩子的每個實例添加到數組中,但是每當我刪除一個孩子然后添加另一個孩子時,它都會重復兩次,將添加的孩子重復一次;如果再次執行,它將重復3次,依此類推。我刪除並添加。 添加和刪除主要在下面的函數中進行,我不知道為什么要復制它們。
func fetchContacts(completion: @escaping () -> ()){
contacts = [Contact]()
let userRef = ref.child("users").child(user).child("contacts")
userRef.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]{
print(snapshot)
let contact = Contact()
contact.setValuesForKeys(dictionary)
self.contacts.append(contact)
}
self.contactsTable.reloadData()
completion()
}, withCancel: nil)
userRef.observe(.childRemoved, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]{
let contact = Contact()
contact.setValuesForKeys(dictionary)
if let i = self.contacts.index(where: { $0.name == contact.name }) {
self.contacts.remove(at: i)
}
}
self.contactsTable.reloadData()
completion()
}, withCancel: nil)
}
這是刪除的處理位置以及在viewDidLoad中如何調用函數:
override func viewDidLoad() {
contactsTable.delegate = self
contactsTable.dataSource = self
contactsTable.rowHeight = 65
super.viewDidLoad()
fetchContacts(){
self.contactsTable.reloadData()
}
}
func handleDelete(phone: String, completion: @escaping () -> ()){
let userRef = ref.child("users").child(user).child("contacts")
userRef.child(phone).removeValue { (error, ref) in
if error != nil {
print("Error: \(error)")
}
completion()
}
}
這可能與您沒有在主線程上調用reloadData()
有關。
不僅僅是:
self.contactsTable.reloadData()
嘗試:
DispatchQueue.main.async {
self.contactsTable.reloadData()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.