【问题标题】:Duplicating data when fetching JSON function called获取调用的 JSON 函数时复制数据
【发布时间】:2017-08-31 15:47:42
【问题描述】:

我的问题是我在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,
    }
}

【问题讨论】:

  • 视情况而定。怎么又叫了?您再次请求相同的数据,不是吗?所以避免再次调用它?还是您在寻找分页 API?
  • @Larme 我在 ViewDidLoad() 上调用 getData() 所以我只在 ViewController 上调用一次。
  • 为什么要重新加载页面?如果它已加载,并且您导航到另一个页面然后返回,您应该只获取 viewDidAppear - 您是否强制卸载视图作为导航的一部分?如果您需要卸载页面,则应在卸载过程中删除所有数据 - 如果保留表单数据有效,则不应删除表单...

标签: ios json swift alamofire swifty-json


【解决方案1】:

只需插入一行即可清空数组:

... 
  let jsonArray = json[].arrayValue
  self.items.removeAll()
  for json in jsonArray {
... 

或替换

for json in jsonArray {
    let item = Items.fromJson(json: json)
    self.items.append(item)
 }

self.items = jsonArray.map { Items.fromJson(json: $0) }

【讨论】:

  • 感谢使用“self.items = jsonArray.map { Items.fromJson(json: $0) }”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-05
  • 1970-01-01
  • 2018-10-21
  • 1970-01-01
  • 2017-11-07
相关资源
最近更新 更多