ios - Firebase .childAdded 在 Xcode 中产生重复输出

标签 ios swift firebase firebase-realtime-database

我有以下代码来观察图片的新评论并显示所有图片的新评论总数:

    let ref4 = DatabaseReference.media.reference()
        let query4 = ref4.child("\(value)/comments")
        query4.observe(.childAdded, with: { snapshot in
         let comment = Comment(dictionary: snapshot.value as! [String : Any])
           self.myNotif.insert(comment, at: 0)

           self.newComment.text = ("\(self.myNotif.count)")
            print("new comment noticed")

问题是,尽管只向数据库添加了一个 child ,但控制台正在复制结果。例如,将有重复的打印语句。这样做的主要问题是它还将计数器增加 2 而不是 1。以前有人遇到过这个吗?

最佳答案

我在我的评论类中添加了一个扩展以包含对公平协议(protocol)的一致性,然后将完成更改为:

    if !self.myNotif.contains(comment) {
           self.myNotif.insert(comment, at: 0)

           self.newComment.text = ("\(self.myNotif.count)")
            print("new comment noticed")
            }

它似乎解决了差异

关于ios - Firebase .childAdded 在 Xcode 中产生重复输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45130377/

相关文章:

ios - 在 UICollectionView 的单元格中显示相同的图像

ios - 如何在 swift 的第二个日期选择器中显示第一个日期选择器的选定日期

ios - 即使我们不像其他 ViewController 生命周期方法一样在 viewcontroller 中重写 loadView ,它也会被调用吗?

ios - 如何分离这两个功能?

Android Firebase 电话号码身份验证更新配置文件错误

ios - 动画雷达叠加 MKMapView iOS

iphone - 关于使用非原子和保留属性(property)

ios - 防止调用子类中的继承方法

ios - 使用 iOS13 使用 NFC 读取 eID 信息时遇到问题

facebook - 如何连接facebook、firebase和flutter?