我的单元格正在重复应用我在在线数据库上进行的更改

时间:2017-08-21 15:54:57

标签: ios swift uitableview firebase firebase-realtime-database

使用此代码,我可以获取数据库的快照并将数据加载到tableView中。但是,当我尝试对在线数据库进行更改时,我会获得应用更改的重复单元格而不是应用此更改的正常单元格。

    // Create reference to databse
    ref = Database.database().reference()

    // Retrieve data from firebase database and listen for changes
    ref.child("Clubs").observe(.value, with: { (snapshot) in
        print("clubs: \(snapshot)")

        if(snapshot.exists()) {
            let array:NSArray = snapshot.children.allObjects as NSArray

            for obj in array {
                let snapshot:DataSnapshot = obj as! DataSnapshot
                if let childSnapshot = snapshot.value as? [String : AnyObject] {
                    print("myClubs: \(childSnapshot)")

                    if let clubName = childSnapshot["name"] as? String, let banner = childSnapshot["bannerImage"] as? String {
                        print(clubName)
                        print(banner)

                        let club = Club(name: clubName, image: banner)
                        print("new club success: \(club)")
                        self.nightClubs.append(club)
                    }
                }
            }

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

        }

    })

1 个答案:

答案 0 :(得分:2)

每当Clubs中的任何值发生变化时,您都会在侦听器中执行代码。该代码将俱乐部附加到nightClubs数组,但不清除它。在重新填充之前需要清空数组:

// Retrieve data from firebase database and listen for changes
    ref.child("Clubs").observe(.value, with: { (snapshot) in
        print("clubs: \(snapshot)")
        self.nightClubs.removeAll() // empty array before adding values

        ...