数组的大小在Swift中总是返回0

时间:2018-05-11 17:28:53

标签: arrays swift nsurlsession

我在Swift中遇到数组问题。 如果我在print(self.days.count)方法中有initialization,我总是在数组中获得正确数量的对象days。但是,如果我在print(self.days.count)内使用viewDidLoad(),我总是得到0.有没有办法可以修复它?我感谢任何帮助。

import UIKit

class ViewController: UIViewController, UITableViewDelegate{
    //object array for weather
    var objectArray = [WeaObject]()
    var days = [List]()
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        initialization {
            print("succ")
            print(self.days.count)
        }
        tableView.delegate = self
        tableView.delegate = self
        print(days.count)
        //print(objectArray.count)
    }

    func initialization(completed:@escaping () -> ()){
        let jsonUrlString="http://api.openweathermap.org/data/2.5/forecast?zip=22003&appid=c632597b1892b4d415c64ca0e9fca1f1"
        guard let url = URL(string: jsonUrlString) else { return }

        URLSession.shared.dataTask(with: url) { (data, response, err) in
            guard let data = data else { return }
            do {
                let downloadDays = try JSONDecoder().decode(TestingClass.self, from: data)
                self.days = downloadDays.list
                DispatchQueue.main.async {
                    completed()
                }
            } catch let jsonErr {
                print("Error serializing json:", jsonErr)
            }
        }.resume()
    }
}

1 个答案:

答案 0 :(得分:1)

您需要在reloadData()完成区内的表格视图上致电initialization

更新viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.delegate = self

    initialization {
        print("succ")
        print(self.days.count)
        tableView.reloadData()
    }

    // Do not print days.count here because days isn't updated yet
}

最好更新主队列上的数据模型:

func initialization(completed:@escaping () -> ()){
    let jsonUrlString="http://api.openweathermap.org/data/2.5/forecast?zip=22003&appid=c632597b1892b4d415c64ca0e9fca1f1"
    guard let url = URL(string: jsonUrlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, err) in
        guard let data = data else { return }
        do {
            let downloadDays = try JSONDecoder().decode(TestingClass.self, from: data)
            DispatchQueue.main.async {
                self.days = downloadDays.list
                completed()
            }
        } catch let jsonErr {
            print("Error serializing json:", jsonErr)
        }
    }.resume()
}

您还应该遵守UITableViewDataSource

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSoure {