在这里,我声明myArray。
class AcikIlanlarViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var myArray: [String] = []
在这里,我调用了loadPage函数来修改数组。
override func viewDidLoad() {
loadPage()
//when printed here myArray is nil
...
func loadPage() {
...
Alamofire.request(url, method: .get, parameters: parameters, encoding: JSONEncoding.default)
.validate { request, response, data in
...
let databases = try JSONDecoder().decode(responseData.self,from: json)
...
for i in 0...databases.orders.count-1 {
myArray.append(databases.orders[i].header!)
}
// when printed here I see the append has worked and myArray is not empty
}
如评论中所述,在viewDidLoad中,我调用loadPage,该页面将某些内容附加到myArray中。在附加之后,我可以看到附加项。但是,在viewDidLoad中,在调用loadPage之后,myArray原来为空。为什么不保存?
答案 0 :(得分:3)
for循环后重新加载表
for i in 0...databases.orders.count-1 {
myArray.append(databases.orders[i].header!)
}
self.tableView.reloadData()
答案 1 :(得分:2)
loadPage()
调用异步方法,因此该功能将在操作完成之前完成。通常,调用异步方法的func
应当具有完成处理程序…
override func viewDidLoad() {
loadPage {
self.tableView.reloadData()
}
}
func loadPage(completion: () -> Void) {
Alamofire.request(url, method: .get, parameters: parameters, encoding: JSONEncoding.default).validate { request, response, data in
let databases = try JSONDecoder().decode(responseData.self,from: json)
for i in 0...databases.orders.count-1 {
myArray.append(databases.orders[i].header!)
}
completion()
}
}