ios - 更改/更新子值而不添加新子项(Firebase-swift)

标签 ios swift firebase firebase-realtime-database

我正在尝试从我的 firebase 数据库更新我的子值,但问题是每当我的子值增加 1 时,我的 tableview 就会自动创建一个新的子值。我怎样才能使它只更新子值?感谢您提前提供的帮助。

注意:请查看图片以更清楚地了解

var ref: DatabaseReference?
var databaseHandle: DatabaseHandle?
var postData = [String]()
var postData2 = [String]()

class TableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        ref = Database.database().reference() //set the firebase reference

        // Retrieve the post and listen for changes
        databaseHandle = ref?.child("Posts").observe(.childChanged, with: { (snapshot) in
            // Code to execute when a child is added under "Posts"
            let post1 = snapshot.key
            let post2 = (snapshot.value as AnyObject).description

            postData.append(post1)
            if let actualPost = post2 {
            postData2.append(actualPost)

            self.tableView.reloadData()

            }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return postData.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = postData[indexPath.row]
        cell.detailTextLabel?.text = postData2[indexPath.row] + " ★"
        cell.detailTextLabel?.textColor = UIColor.yellow;
        return cell
    }

}

Image

最佳答案

当您从列表中添加元素时,数据源计数会增加 1,但随后将调用 childAdded 的 Firebase 回调,现在您检索从数据库添加的相同元素,从而导致重复行。

您的示例中不存在按下红色按钮时运行的调用,但我假设您按照这些方式做了一些事情。希望对您有所帮助。

关于ios - 更改/更新子值而不添加新子项(Firebase-swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47503206/

相关文章:

ios - 为 ios 构建 Cordova 应用程序时更改消失

ios - 自定义运算符来简化 If-Let

uitableview - 无法展开 Optional.None。我无法弄清楚如何或什么

iOS 在展开可选值时意外发现 nil

angular - 将 firebase 响应映射到类

firebase - Pushsharp 4.0 与 Firebase

python - 如何从 Firebase 实时数据库获取最新记录

ios - 为什么当我在 swift 3 中从图库中获取照片时, Collection View 为空?

objective-c - 使 UITableView 的单元格水平对齐而不是垂直对齐

swift - 是否可以在 swift 中手动释放静态变量?