我试图让我的程序将一个 child 的每个实例添加到一个数组中,但是每当我删除一个 child 然后添加另一个它重复添加的 child 两次,如果我再次这样做,它将重复 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()
}
关于ios - Firebase .childAdded 观察者复制 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44803946/