【发布时间】:2017-06-28 13:29:55
【问题描述】:
我正在尝试让我的程序将子项的每个实例添加到一个数组中,但是每当我删除一个子项然后添加另一个子项时,它就会重复添加的子项两次,如果我再次这样做,它将重复 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()
}
}
【问题讨论】:
标签: ios firebase swift3 firebase-realtime-database