1

I am trying to have my program add every instance of a child to an array but whenever I delete a child then add another it duplicates that added child twice and if I do it again it will duplicate 3 times and so on depending on how many times I delete and add. The adding and deleting is mainly handled in the function below and I can't figure out why it is duplicating them.

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)
}

Here is where the deleting is handled and how the functions are called in the 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()
    }
}

1 Answer 1

2

This may be to do with you not calling reloadData() on the main thread.

Instead of just:

self.contactsTable.reloadData()

try:

DispatchQueue.main.async {
    self.contactsTable.reloadData()
}
3
  • In the viewDidLoad? Commented Jun 28, 2017 at 13:44
  • @BenCavenagh wherever you call self.contactsTable.reloadData() Commented Jun 28, 2017 at 13:45
  • I'm an idiot. I was accidentally calling the fetchContacts function multiple times. Thanks for helping though, your answer helped me find that second call. Commented Jun 28, 2017 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.