【问题标题】:How to avoid crashes in tableView(_:cellForRowAt)?如何避免 tableView(_:cellForRowAt) 中的崩溃?
【发布时间】:2018-09-23 12:39:08
【问题描述】:

在 Fabric 中,我在“tableView(_:cellForRowAt)”部分看到了很多崩溃。这种例外情况没有特定的情况。它可以在任何时间和任何屏幕上发生。没有用于分析崩溃的数据。只有我知道“tableView(_:cellForRowAt)”中有崩溃。

虽然我不知道根本原因,但我想防止这种异常。我可以使用防止 NullPointer Exception (if (!null)) 之类的方法吗?

以下两个不同代码部分的崩溃;

let XXX = Constants.sharedInstance.url+"/service/photo/"+userdas[(indexPath as NSIndexPath).row].id!+"/"+userdas[(indexPath as NSIndexPath).row].photo!+"/2"

self.notificationModel[indexPath.row].userNot.XXX?.XXXImageView = image

【问题讨论】:

  • 请将tableView(_:cellForRowAt) 方法的代码添加到问题中
  • 可能你在你的方法中做了一些显式或隐式的强制解包,这会导致崩溃。添加您的方法的代码,以便我们可以肯定地说。
  • 不同代码段的两次崩溃; 1- 让 XXX=Constants.sharedInstance.url+"/service/photo/"+userdas[(indexPath as NSIndexPath).row].id!+"/"+userdas[(indexPath as NSIndexPath).row].photo!+ "/2" 2- self.notificationModel[indexPath.row].userNot.XXX?.XXXImageView = image
  • @YuryImashev 我添加了发生崩溃的行。

标签: ios swift uitableview


【解决方案1】:

从您的代码中可以清楚地看出,您正在执行一些可能导致崩溃的显式强制解包。

userdas[(indexPath as NSIndexPath).row].id!

userdas[(indexPath as NSIndexPath).row].photo!

self.notificationModel[indexPath.row].userNot.XXX?.XXXImageView

我猜在第三种情况下XXXImageView 被隐式解包UIImageView 也可能是nil

为了避免第一部分的崩溃,您可以使用guard

guard let id = userdas[indexPath.row].id, 
      let photo = userdas[indexPath.row].photo else {
    return 
}
let XXX = Constants.sharedInstance.url+"/service/photo/"+id+"/"+photo+"/2"

我不确定您在第二部分中在做什么,但您只需要检查您展开的参数是否也不是 nil

【讨论】:

  • 非常感谢@YuryImashev
  • @AshleyMills 当然!感谢您的建议,答案已更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
相关资源
最近更新 更多