My problem is I have the function getData()
on the ViewDidLoad()
and when i switch to another view and go back to this view it loads again the Data which duplicates my Data on the tableView.
我的问题是我在ViewDidLoad()上有函数getData(),当我切换到另一个视图并返回到该视图时,它再次加载数据,该数据在tableView上复制我的数据。
var items = [Items]()
func getData() {
Alamofire.request(url, method: .get).validate().responseJSON { response in
self.obj.helper.checkConnectivity()
switch response.result {
case .success(let value):
let json = JSON(value)
let jsonArray = json[].arrayValue
for json in jsonArray {
let item = Items.fromJson(json: json)
self.items.append(item)
}
case .failure(let error):
print(error)
}
self.tableView.reloadData()
}
}
struct Items {
var id: Int
var name: String
static func fromJson(json: JSON) -> Items {
return Items(
id: json["id"].intValue,
name: json["name"].stringValue,
}
}
1 个解决方案
#1
1
Just insert a line to clear the array:
只需插入一行即可清除数组:
...
let jsonArray = json[].arrayValue
self.items.removeAll()
for json in jsonArray {
...
or replace
或替换
for json in jsonArray {
let item = Items.fromJson(json: json)
self.items.append(item)
}
with
同
self.items = jsonArray.map { Items.fromJson(json: $0) }
#1
1
Just insert a line to clear the array:
只需插入一行即可清除数组:
...
let jsonArray = json[].arrayValue
self.items.removeAll()
for json in jsonArray {
...
or replace
或替换
for json in jsonArray {
let item = Items.fromJson(json: json)
self.items.append(item)
}
with
同
self.items = jsonArray.map { Items.fromJson(json: $0) }