【问题标题】:Crash at tableview.reloaddata with error Unexpectedly found nil在 tableview.reloaddata 崩溃并出现错误 Unexpectedly found nil
【发布时间】:2018-11-23 05:30:19
【问题描述】:

单击创建按钮后,我导航到 tableviewcontroller 屏幕。但是表格视图中没有填充任何内容,因为尚未调用填充表格视图的数组。

现在,一旦到达 tableview 屏幕,几秒钟后,另一个方法会在其他地方(在另一个文件中)调用,该方法又会调用此 tableviewcontroller 屏幕中的函数。这是tableviewcontroller屏幕的那个方法,被称为...

  func stopIndicator(thegrpName: String) {
    stopIndicator()

    let realm = try! Realm()
    let chatGrp = realm.objects(ChatGroup.self)
    chatGroup = chatGrp

    tableview.reloadData() //CRASH HAPPENS HERE

  }

在这种方法中,一旦我到达tableview.reloadData(),它就会崩溃并出现错误Unexpectedly found nil while unwrapping an optional value..

我提到了this 链接,它似乎有类似的问题...但无法从中获得太多帮助...

这次崩溃的原因可能是什么...?

编辑 1:numberOfRows 和 cellForRowAt.. 是这样给出的...

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if let chatGrp = chatGroup {
      return chatGrp.count
    }
    return 0
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: ChatGroupTableViewCell = tableView.dequeueReusableCell(withIdentifier: "chatgroupIdentifier") as! ChatGroupTableViewCell

    let groupChatObj = chatGroup![indexPath.row]
    cell.chatLabel.text = groupChatObj.lastMessage?.text?.text
    return cell
  }

【问题讨论】:

  • 请出示您的numberOfRowsInSectioncellForRowAt 方法。另请参阅 this 了解一般故障排除和针对此异常的建议
  • 似乎tableview nil,如果它添加到情节提要中,请检查插座是否连接。
  • 检查@Satish..其连接正确..
  • 设置异常断点查看哪一行崩溃了。
  • 不要使用感叹号(“!”),而是使用可选的展开,如果您尝试展开的值为 nil,则打印一些内容。这样,您就可以准确地知道哪个值是 nil,而不必猜测。

标签: ios swift uitableview


【解决方案1】:

看起来您正在尝试创建委托方法,但在另一个文件中您尝试调用委托方法 stopIndicator 您正在调用单例方法而不是给您一个错误。

所以,设置代理权。首先创建协议

protocol YourProtocol {
    func stopIndicator(thegrpName: String)
}

然后在另一个文件中创建委托属性

var delegate: YourProtocol?

现在当你需要调用委托方法 stopIndicator 时调用这个

delegate?.stopIndicator(thegrpName: ...)

现在添加到您的 ViewController 协议中

ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, YourProtocol

现在在某处将您的另一个文件类委托设置为您的 ViewController(如果它的视图在 viewDidLoad 中设置它,如果它是另一个 ViewController,则在 prepareForSegue 中设置它)

fileClass.delegate = self 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 2022-06-24
    相关资源
    最近更新 更多