【发布时间】:2018-05-12 12:17:14
【问题描述】:
问题:
当我从数据源重新加载数据时,我希望我的 tableView 清除旧单元格。当我在展开 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()
}
}
}
}
【问题讨论】:
-
那是因为您在向其中添加新记录之前没有清除数据源数组。
-
@BenJ 你能分享所有相关代码吗?我的意思是与 getNewDataAndUpdateTable() 函数相关的完整代码?
标签: ios swift uitableview