【问题标题】:How to delete Firebase snapshot from array?如何从阵列中删除 Firebase 快照?
【发布时间】:2016-10-28 16:20:51
【问题描述】:

我有一个函数可以监听添加到 Firebase 数据库的新对象,将这些新对象附加到一个数组中,然后使用该数组填充一个 tableView。一旦对象被删除,我不知道如何从数组中删除它。我认为我在正确的轨道上,但我不知道如何“撤消”追加。

这是我目前所拥有的:

func configureDatabase() {

    // Listen for new messages in the Firebase database
    let ref = self.rootRef.child("invites").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in

    self.invites.append(snapshot)
    self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.invites.count-1, inSection: 0)], withRowAnimation: .Automatic)
    })

    //listen for deleted messages in Firebase database
    let ref2 = self.rootRef.child("invites").observeEventType(.ChildRemoved, withBlock: { (snapshot) -> Void in

     //remove from invites array and refresh table??
    })
}

我必须从表格中的实际单元格传递值吗?

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("AlertCell", forIndexPath: indexPath) as! AlertCell

        //get user, set cell text
        let inviteDict = invites[indexPath.row].value as! [String : AnyObject]
}

【问题讨论】:

    标签: arrays swift firebase swift2 firebase-realtime-database


    【解决方案1】:

    我在 Firebase 网站上的示例代码中找到了答案:

    // Listen for deleted comments in the Firebase database
        commentsRef.observeEventType(.ChildRemoved, withBlock: { (snapshot) -> Void in
          let index = self.indexOfMessage(snapshot)
          self.comments.removeAtIndex(index)
          self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 1)], withRowAnimation: UITableViewRowAnimation.Automatic)
        })
    
    func indexOfMessage(snapshot: FIRDataSnapshot) -> Int {
        var index = 0
        for  comment in self.comments {
          if (snapshot.key == comment.key) {
            return index
          }
          index += 1
        }
        return -1
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 2018-03-12
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      相关资源
      最近更新 更多