【问题标题】:Swift UIViewController tableView.reloadData nil wrapping on second callSwift UIViewController tableView.reloadData nil 在第二次调用时包装
【发布时间】:2016-11-03 15:42:43
【问题描述】:

多次搜索都没有成功。在 viewDidLoad 上的视图控制器中,我调用了一个名为 callJson 的函数。然后它设置绑定到 UITableView 的数据。这一切都是第一次很好。现在我也有一个 UIRefreshControl,当我拉它时,它会调用同一个函数 callJson,在第二次尝试时,我得到了臭名昭著的错误

致命错误:在展开可选值时意外发现 nil 关于 self.tableView.reloadData()

这是向 json 发出请求并说用新数据重新加载表的函数。

func callJson(){
    JSONOperations.sharedInstance.JsonRequest(roadType: Helpers.RoadWayTypes.ALERTS, imageId: nil) {(json: NSDictionary) in
        do {
            //unbox alerts
            let aData: Alerts = try unbox(dictionary: json as! UnboxableDictionary)
            self.alerts = aData
            self.tableView.reloadData()
        }
        catch {
            print(error)
        }
    }
}

tableView 设置单元格数据

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let alertD = alerts?.Alerts[indexPath.row] {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "AlertTableViewCell") as! AlertTableViewCell
        cell.name.text = alertD.Summary
        cell.icon.image = Helpers.listImage24dp(id: alertD.TOA)
        cell.selectionStyle = .none
        if alertD.Url.characters.count == 0 {
            cell.isUserInteractionEnabled = false
            return cell
        }
        cell.isUserInteractionEnabled = true
        cell.name.textColor = UIColor.blue
        return cell
    }
    return UITableViewCell()
}

当我在 self.tableView.reloadData() 之前设置断点并进入时,它会转到定义的出口,但随后会引发 nil 错误。我不确定是否需要在 tableView 或其他内容中进行不同的设置,因为它第一次正常工作。感谢您提供任何帮助/想法。

【问题讨论】:

  • 你确定你设置了tableview的outlet?
  • 是的,否则,它不会在第一次工作,除非由于某种原因插座在第一次通话和第二次通话之间掉线,如果是这样,我不明白为什么或如何去做恢复它。

标签: ios uitableview


【解决方案1】:

请使用下面的。

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

原因: tableview 重新加载应该发生在 UI 线程中。

【讨论】:

  • 把它放在闭包中并没有改变任何东西。第一次仍然有效,但第二次无效。同样的错误。
猜你喜欢
  • 2013-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 2018-08-23
相关资源
最近更新 更多