【问题标题】:Firebase .childAdded observer duplicating childrenFirebase .childAdded 观察者复制孩子
【发布时间】: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


    【解决方案1】:

    这可能与你没有在主线程上调用reloadData()有关。

    不仅仅是:

    self.contactsTable.reloadData()
    

    尝试:

    DispatchQueue.main.async {
        self.contactsTable.reloadData()
    }
    

    【讨论】:

    • 在viewDidLoad中?
    • @BenCavenagh 无论您打电话到哪里self.contactsTable.reloadData()
    • 我是个白痴。我不小心多次调用了 fetchContacts 函数。不过感谢您的帮助,您的回答帮助我找到了第二个电话。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 2018-04-23
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多