【问题标题】:Error with UI Table View + asynchronously loaded dataUI 表视图错误 + 异步加载的数据
【发布时间】:2019-03-29 21:54:26
【问题描述】:

我有一个 UI Table VIew,其中包含从 URL 异步加载的数据。对于

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (self.notificationsResponse?.data?.count)!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let notification = notificationsResponse?.data![indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! NotificationsViewCell
    cell.setNotification(notification: notification!)
    return cell
}

var notificationsResponse:NotificationsResponse?

我收到类似

的错误

线程 1:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)

在这一行

return (self.notificationsResponse?.data?.count)!

我不知道这有什么问题。我正面临这个问题,可能是由于对 swift 理解不佳

谁能帮帮我?

【问题讨论】:

  • 避免强制展开(使用!)。据我猜测,它是异步的,所以响应还没有出现,所以你会崩溃。改用return self.notificationsResponse?.data?.count ?? 0 之类的方法。
  • 可选链接失败 + 强制解包 = 崩溃。
  • 谢谢@Larme 这很好用。
  • 避免强制展开 (!)。如果您不是 100% 存在价值,这将使您的应用程序崩溃。当涉及到异步调用时,请确保更新主线程上的值。
  • 除了这个问题,强烈建议您不要使用 通知响应 作为数据源数组。

标签: ios swift swift3 swift4


【解决方案1】:

您可以像这样编写使用强制展开的行

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    guard let data = self.notificationsResponse?.data else { return 0 }
    return data.count
}

编辑:其他答案实际上更好哈哈。但是守卫也是防止强制展开的好方法。

【讨论】:

    【解决方案2】:
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (self.notificationsResponse?.data?.count)!
    }
    

    请改一下

    return self.notificationsResponse?.data?.count ?? 0
    

    【讨论】:

      猜你喜欢
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      相关资源
      最近更新 更多