Swift 如何通过 dispatch_queue 更新 tableview 单元格

标签 swift dispatch-async

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

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 从服务器获取。我认为原因是在获取 dictAnswer 之前更新了单元格。但我不知道如何使用 dispatch_async。我希望有一些可以给我提示。谢谢

最佳答案

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

关于Swift 如何通过 dispatch_queue 更新 tableview 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37364870/

相关文章:

ios - 第二次按下按钮时 3D 对象的放置不起作用

ios - 将图像从 Web 服务加载到 UIImage 无法正常工作

testing - 像 dispatch_async 这样的代码的单元测试。

swift - 需要澄清在 Swift 中对文字使用点符号

ios - 由于未捕获的异常而终止应用程序,原因 : 'attempt to delete row 3 from section 1 which only contains 0 rows before the update'

ios - 为什么从后台线程更新 UI 需要这么长时间?

IOS/objective-C : returning to main thread

ios - 应用响应时在 Xcode-Swift 中呼吸动画

ios - 无法在我的 iOS 应用程序中读取 XML 文件

ios - Xcode UI 测试 - 与测试管理器服务失去连接