[英]How to save the result of a @escaping closure function into a viewcontroller class property variable?
I always get an empty value in my variable var services:[String] = [""]
here is my code: 我总是在变量
var services:[String] = [""]
得到一个空值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
}
}
}
}
I tried several methods but I always get an empty value in my tableviewCell because the variable services:[String] = [""]
despite being assigned in the function 我尝试了几种方法,但是我总是在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
}
}
}
}
Your WebApi().listeService()
is running asynchronously, so you exit viewDidLoad()
before the data is available. 您的
WebApi().listeService()
正在异步运行,因此在数据可用之前退出viewDidLoad()
。
You need to call tableView.reloadData()
after you set self.services = listeServices
设置
self.services = listeServices
后,需要调用tableView.reloadData()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.