【问题标题】:swift and unexpectedly found nil while unwrapping an Optional value在展开可选值时迅速并意外发现 nil
【发布时间】:2016-02-21 11:57:31
【问题描述】:

我有一堂课:

class ListOfEventsController: UIViewController, UITableViewDataSource, UITableViewDelegate {

它包含一个函数:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("CELL") as! SingleEventCell

当我运行它时 - 它会导致错误提示

fatal error: unexpectedly found nil while unwrapping an Optional value

但是当我去我的故事板时,我看到:

当我点击CELL 时,我会在其属性中看到:

还有:

所以CELL 的标识符已设置,但我仍然收到此错误。

我还能做什么?

【问题讨论】:

  • 改变你的 if cell = ...... 到 if let cell = .........
  • 尝试 dequeueReusableCellWithIdentifier:forIndexPath 方法
  • @sateesh 我试过了,但是当我运行应用程序时,我看到 Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier CELL - must register a nib or a class for the identifier or connect a prototype cell in a storyboard' 这很奇怪,因为 - 正如你在我的屏幕截图中看到的 - CELL 被用作标识符......跨度>
  • 在你的视图中注册一个笔尖确实加载方法,这个错误是在说类似的事情
  • 我看到您在下面选择了一个答案。正如我在另一个问题中所知道的那样,这是否解决了您的问题,这没有帮助。

标签: ios swift uitableview xcode-storyboard


【解决方案1】:
  1. 在 Storyboard 中选择您的原型单元
  2. alt + cmd + 4 打开属性检查器
  3. CELL 写入Identifier 字段。

然后再试一次;)

【讨论】:

  • 谢谢,但这正是我一开始所做的 :) 只需检查我原始问题中的最后一个屏幕截图 - 它与您的完全相同;)
  • @user3766930:好的,那么请尝试清理整个项目:Xcode > Product > Clean。然后重置模拟器并重试。
  • 这就是我正在做的事情:imgur.com/a/vZl26 是故事板中的错误字段吗?
  • 不幸的是,清理在这里没有帮助,我必须做错事,但我不知道这里有什么问题......
  • @user3766930:据我所知,你做的一切都是对的。您确定故事板中定义的UITableView 是您在代码中使用的SAME UITableView
【解决方案2】:
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CELL"];

解决你的问题。

【讨论】:

  • 你应该先注册一个类,然后再将你的单元格放入 cellforrowatindexpath
  • 谢谢,你能给我一个更大的提示吗? :) 我不知道该怎么办,抱歉 :(
  • 如果单元格是在情节提要中设计的,则不需要。
【解决方案3】:

试试

let cell = tableView.dequeueReusableCellWithIdentifier("CELL", forIndexPath: indexPath) as! SingleEventCell

【讨论】:

  • 我收到一条错误消息:'unable to dequeue a cell with identifier CELL - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
  • 您是否单击了故事板中的原型单元并将其命名为 CELL?对于命名约定,在故事板和上述代码中重命名“CELL”>“Cell”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 2016-10-18
  • 2017-04-09
  • 2018-09-22
相关资源
最近更新 更多