[英]numberOfRowsInSection is called before Alamofire connection
I get data by Alamofire in viewDidLoad
, then put it into answerArray. 我在
viewDidLoad
获取Alamofire的数据,然后将其放入answerArray。 However, before Alamofire connection, the numberOfRowsInSection
is invoked and returns 0. How can I get data by Alamofire first, then get eventArray.count
at numberOfRowsInSection
? 但是,在Alamofire连接之前,调用
numberOfRowsInSection
并返回0.如何首先通过Alamofire获取数据,然后在numberOfRowsInSection
获取eventArray.count
?
var answerArray = NSMutableArray()
override func viewDidLoad() {
let parameters = [
"id":questionNum
]
Alamofire.request(.POST, "http://localhost:3000/api/v1/questions/question_detail",parameters: parameters, encoding: .JSON)
.responseJSON { (request, response, JSON, error) in
println(JSON!)
// Make models from JSON data
self.answerArray = (JSON!["answers"] as? NSMutableArray)!
}
self.tableView.reloadData()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return answerArray.count
}
The behavior is normal. 行为很正常。
UITableView
delegate invokes numberOfRowsInSection
as needed. UITableView
委托根据需要调用numberOfRowsInSection
。
All you need is to trigger self.tableView.reloadData()
to refresh the table. 您只需要触发
self.tableView.reloadData()
来刷新表。
Alamofire.request(.POST, "http://localhost:3000/api/v1/questions/question_detail",parameters: parameters, encoding: .JSON)
.responseJSON { (request, response, JSON, error) in
println(JSON!)
// Make models from JSON data
self.answerArray = (JSON!["answers"] as? NSMutableArray)!
self.tableView.reloadData()
}
I think more elegant way would be reloading tableView every time you assign to answerArray
so that tableView will be updated automatically whenever you get a response from your API. 我认为每次分配给
answerArray
,更优雅的方法是重新加载tableView,以便每当您从API获得响应时tableView都会自动更新。
Move self.tableView.reloadData()
into didSet
callback. 将
self.tableView.reloadData()
移动到didSet
回调中。
var answerArray = NSMutableArray() {
didSet {
self.tableView.reloadData()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.