在Alamofire连接之前调用numberOfRowsInSection
我在viewDidLoad
通过Alamofire获取数据,然后将其放入答案数组中。 但是,在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 }
行为是正常的。 UITableView
委托根据需要调用numberOfRowsInSection
。
所有你需要的是触发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() }
我认为更优雅的方式将重新加载tableView每次你分配给answerArray
这样tableView将自动更新,每当你从你的API的响应。
将self.tableView.reloadData()
移动到didSet
callback。
var answerArray = NSMutableArray() { didSet { self.tableView.reloadData() } }