Swift如何调度_队列以更新tableview单元格

Swift如何调度_队列以更新tableview单元格,swift,dispatch-async,Swift,Dispatch Async,在加载tableview之前,我的应用程序需要从服务器获取数据。 如何使用dispatch_async使应用程序在完成获取数据后更新单元格视图 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = myTable.dequeueReusableCellWithIdentifier("editCell")

在加载tableview之前,我的应用程序需要从服务器获取数据。 如何使用dispatch_async使应用程序在完成获取数据后更新单元格视图

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = myTable.dequeueReusableCellWithIdentifier("editCell") as! EditTableViewCell

    cell.answerText.text = dictPicker[indexPath.row]![dictAnswer[indexPath.row]!]
    cell.questionView.text = listQuestion1[indexPath.row]
    cell.pickerDataSource = dictPicker[indexPath.row]!
    dictAnswer[indexPath.row] = cell.pickerValue
    cell.answerText.addTarget(self, action: #selector(AddFollowUpViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingDidEnd)
    cell.answerText.tag = indexPath.row
    cell.identifier = true

    return cell
}

当我使用上面的代码时,它给了我一个错误:dictAnswer是nil。dictAnswer是从服务器获取的。我认为原因是在获取口述答案之前更新了单元格。但是我不知道如何使用dispatch\u async。我希望有人能给我一个提示。THX

这是重新加载数据的方式。但请记住在启动之前刷新阵列 重新加载数据。请记住,仅仅获取数据并不重要,在重新加载之前将数据更新到数组中也很重要

dispatch_async(dispatch_get_main_queue(), {() -> Void in
            self.tableView.reloadData()
        })

UITableViewDataSource函数应该引用数组中的行数,如下所示

var data:[String]()

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

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

    }
因此,在获取数据的异步函数中,您可以执行以下操作:

func loadData() {
     // some code to get remote data
     self.data = result
     dispatch_async(dispatch_get_main_queue()) {
         tableView.reloadData()
     }
}
当数组为空时,(data.count返回0),tableView不会尝试加载任何行并崩溃

更新Swift 3+:

DispatchQueue.main.async {
    tableView.reloadData()
}

在使用Scriptable的答案后,我不得不进行一些更新,并认为将它们发布回这里是一个好主意

Swift 3

DispatchQueue.main.async(execute: { () -> Void in
                    self.tableView.reloadData()
                })

DispatchQueue.main.async {
    self.tableView.reloadData()
}