当我调用reloadData()时,UITableview会将旧单元格添加到旧单元格下方

时间:2018-05-12 12:17:14

标签: ios swift uitableview

问题:

当我从数据源重新加载数据时,我希望我的tableView清除旧单元格。当我在unwind segue上加载表时,数据源从json blob获取所有新数据,但是当我调用reloadData()时,表中的旧单元仍然存在,即使我的数据源数组包含只有新数据。

代码:

主视图控制器:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var sourceArray=[String]()
    var otherClassVariable: Any?

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sourceArray.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
        cell.textLabel?.text = sourceArray[indexPath.row]
        return cell
    }

    func getNewDataAndUpdateTable() {
        //Remove all from sourceArray
        self.sourceArray.removeAll()
        let param = self.otherClassVariable
        let url = URL(string: "https://myurl.com/"+param)!

        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in

            if error != nil {
                print(error as! String)
            } else {
                if let urlContent = data {
                    do {
                        let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as! Array<Dictionary<String, Any>>

                        //Repopulate source Array
                        for thing in jsonResponse {
                            self.sourceArray.append(thing)
                        }

                        Dispatch.main.async {
                            //Reload data in main thread
                            self.tableView.reloadData()
                        }
                    } catch {
                        print("json failed")
                    }
                }
            }
        }

        task.resume()

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        getNewDataAndUpdateTable()

    }

    @IBAction func unwindToViewController(_ sender: UIStoryboardSegue) {
        if sender.source is SecondViewController {
            if let senderVC = sender.source as? SecondViewController{
                self.otherClassVariable = senderVC.updatedOtherClassVariable as String!
                getNewDataAndUpdateTable()
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

之所以如此,是因为您要将新数据附加到sourceArray,但您应该将其分配。

更新代码:

func getNewDataAndUpdateTable() {
    //Remove all from sourceArray
    self.sourceArray.removeAll()
    let param = self.otherClassVariable
    let url = URL(string: "https://myurl.com/"+param)!

    let task = URLSession.shared.dataTask(with: url) {(data, response, error) in

        if error != nil {
            print(error as! String)
        } else {
            if let urlContent = data {
                do {
                    let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as! Array<Dictionary<String, Any>>

                    //Repopulate source Array
                    self.sourceArray = jsonResponse // Assign response to the source array

                    Dispatch.main.async {
                        //Reload data in main thread
                        self.tableView.reloadData()
                    }
                } catch {
                    print("json failed")
                }
            }
        }
    }

    task.resume()

}