如何将@escaping闭包函数的结果保存到viewcontroller类属性变量中?

时间:2018-03-27 16:31:09

标签: ios uitableview viewcontroller

我的变量var services:[String] = [""]总是得到一个空值,这是我的代码:

var services:[String] = [""]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    serviceList()
    print("SERVICE NOM " + services[0])
    serviceTable.delegate = self
    serviceTable.dataSource = self
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     print("service: " + String(services.count))
        return services.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CellService", for: indexPath) as! ServiceViewCell

    //let serviceName = services[indexPath.row]


        cell.lblNomService?.text = self.services[indexPath.row]

        print("service name: " + self.services[indexPath.row])

        cell.swSelectService?.isOn = false

    return cell
}

func serviceList(){
    WebApi().listeService(){ liste, error in

        print("LISTE SERVICE VC: \(String(describing: liste?.count))")
        if (liste?.count != nil && (liste?.count) != 0){
            //print("liste: " + String(describing: liste?.count))
            DispatchQueue.main.async() {
                var listeServices = [""]
                var i = 0
                for row in liste! {
                    i = i + 1
                    print("service name: " + String(i) + row.nom!)
                    listeServices.append(row.nom!)
                }

                self.services = listeServices
            }
        }

    }
}

我尝试了几种方法,但我总是在tableviewCell中得到一个空值,因为变量services:[String] = [""]尽管在函数中被赋值

func serviceList(){
    WebApi().listeService(){ liste, error in

        print("LISTE SERVICE VC: \(String(describing: liste?.count))")
        if (liste?.count != nil && (liste?.count) != 0){
            //print("liste: " + String(describing: liste?.count))
            DispatchQueue.main.async() {
                var listeServices = [""]
                var i = 0
                for row in liste! {
                    i = i + 1
                    print("service name: " + String(i) + row.nom!)
                    listeServices.append(row.nom!)
                }

                self.services = listeServices
            }
        }

    }
}

1 个答案:

答案 0 :(得分:0)

您的<input type="file" name="files" id="photos" /> <script> $("#photos").kendoUpload({ localization: { headerStatusUploaded: "Loading Your Language" } }); 正在异步运行,因此您需要在数据可用之前退出WebApi().listeService()

您需要在设置viewDidLoad()后调用tableView.reloadData()