簡體   English   中英

在Alamofire連接之前調用numberOfRowsInSection

[英]numberOfRowsInSection is called before Alamofire connection

我在viewDidLoad獲取Alamofire的數據,然后將其放入answerArray。 但是,在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()
}

我認為每次分配給answerArray ,更優雅的方法是重新加載tableView,以便每當您從API獲得響應時tableView都會自動更新。

self.tableView.reloadData()移動到didSet回調中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM