dispatch_async()块在UITableViewDataSource方法之前没有完成

时间:2015-08-02 21:48:42

标签: ios swift uitableview

有一个UITableView,其单元格将由HTTP post请求获取的数据填充。但是在数据到来之前执行了UITableView个函数。当应用程序启动时,执行所有三个tableView方法,然后应用程序抛出运行时错误。我想这是因为在cellForRowAtIndexPath中,messageList仍为空。

以下是代码:

class messageViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

    var authData : NSDictionary = [:]
    var funcLib = functionLibrary()
    var messagesList : NSArray = []
    var messageCount: Int = 0

    @IBOutlet weak var messageTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        var authCode = self.authData["auth"] as! String
        var userID = self.authData["user_id"] as! String
        var messageRequsetBodyData: AnyObject = ["op":"users","op2":"getThisWeekMessages","id":"\(userID)","id2":"","id3":"","authCode":"\(authCode)"] as AnyObject

        funcLib.HTTPPostRequest("http://asdasd.asdasdasd.com/services/index.php", bodyData: messageRequsetBodyData){data in

            dispatch_async(dispatch_get_main_queue()){

                if let data = data{

                    var messaggesListDic = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
                    println("------MESSAGGES---------")

                    self.messageCount = messaggesListDic["count"] as! Int
                    //self.messages = messaggesListDic["messages"] as! NSDictionary
                    self.messagesList = messaggesListDic["messages"] as! NSArray
                    println("\(self.messagesList)")
                    self.messageTableView.reloadData()
                }

            }

        }

        self.messageTableView.delegate = self
        self.messageTableView.dataSource = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func dismissMessageVC(sender: AnyObject) {

        self.dismissViewControllerAnimated(true, completion: nil)
    }


    func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        println("asdasd")
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        println("asdasd")
        println("\(self.messageCount)")
        return 1
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        println("bdbsdbsdb")
        var cell = self.messageTableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? UITableViewCell
        let row = indexPath.row
        cell!.textLabel!.text = self.messagesList[0]["content"] as? String
        return cell!
    }

运行时错误说明:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'

我尝试使用cell.textLabel?.text = "asdasd"命令分配单元格标签,它可以正常工作。因此我认为网点或方法没有问题。

如何在使用不同方式执行messageList之前将数据分配到cellForRowAtIndexPath

3 个答案:

答案 0 :(得分:3)

是的,如果您有一个需要进行异步调用以检索数据的表视图,您应该期望在异步请求完成之前调用表视图数据源方法。但是,当异步请求完成时,当您只是调用tableView.reloadData()时,将再次调用表视图数据源方法。这是一种非常常见的模式。

这里的问题是,这个代码没有优雅地处理第一次调用表视图数据源方法时没有数据显示的情况。如果numberOfRowsForSection返回0直到检索到数据(正如其他人所描述的那样,特别是通过返回messagesList.count(),如John和Yedidya建议的那样,而不是返回一个固定的数字),所有都是好。

答案 1 :(得分:1)

即使您的消息计数为零,也会返回行数的常量值。最好返回消息计数。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    println("asdasd")
    println("\(self.messageCount)")
    return self.messageCount;
}

答案 2 :(得分:0)

numberOfRows函数返回值替换为messagesList.count

相关问题