numberOfRowsInSection is called before Alamofire connection

不羁的心 提交于 2019-12-30 07:17:10

问题


I get data by Alamofire in viewDidLoad, then put it into 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?

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

}

回答1:


The behavior is normal. UITableView delegate invokes numberOfRowsInSection as needed.

All you need is to trigger self.tableView.reloadData() to refresh the table.

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()
}



回答2:


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.

Move self.tableView.reloadData() into didSet callback.

var answerArray = NSMutableArray() {
    didSet {
        self.tableView.reloadData()
    }
}


来源:https://stackoverflow.com/questions/31498531/numberofrowsinsection-is-called-before-alamofire-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!