【问题标题】:instantiateViewControllerWithIdentifier is crashing (found nil)instantiateViewControllerWithIdentifier 崩溃(发现为零)
【发布时间】:2015-10-07 14:35:19
【问题描述】:

当我在 iPhone 上尝试 instantiateViewControllerWithIdentifier 时,应用程序会崩溃,尽管这在 ios 模拟器上运行良好。我使用的代码是:

let questionsGameVC: QuestionsGame = self.storyboard?.instantiateViewControllerWithIdentifier("Questions") as! QuestionsGame

它说的错误是

致命错误:在展开可选值时意外发现 nil

有人可以在出错的地方添加任何内容吗?

【问题讨论】:

  • 崩溃是什么错误
  • 对不起,它说:'致命错误:在展开可选值时意外发现 nil'
  • 好吧,这一行无法分辨,但看起来您正在尝试使用其中包含 nil 的东西
  • 但它在模拟器上运行良好,只是在 iPhone 上不行?

标签: swift uiviewcontroller storyboard ios-simulator


【解决方案1】:

有很多地方可能会出错。我会在该行设置一个断点并查看系统的状态,但调试 swift 仍然不是很好。一种替代方法是拆分该行代码并测试所有部分。像这样的:

if let storyboard = self.storyboard {
    if let viewController = storyboard.instantiateViewControllerWithIdentifier("Questions") {
        if let questionGame = viewController as? QuestionGame {
            println("Success!")
        } else {
            println("Question game is the wrong type in the storyboard")
        }
    } else {
        println("There is no view controller with the identifier Questions")
    }
} else {
    println("The storyboard is nil")
}

无论最后打印什么,都应该让您更好地了解问题出在哪里。大多数情况下,我看到拼写错误的标识符或情节提要中视图控制器的类没有从UIViewController 更改为自定义类型的情况。

【讨论】:

  • 什么都没有被打印出来,它在线上崩溃:如果让 viewController = storyboard.instantiateViewControllerWithIdentifier("Questions") ,我在该行之前放了一个 println 并打印了......
  • 我刚刚测试过,很抱歉 - 当没有具有该标识符的视图控制器时,我的代码也崩溃了。我相信这是你的问题。你能确认你的QuestionGame视图控制器的“Storyboard ID”是“Questions”吗?
  • 谢谢,是的,它 100% 是“问题”。就像我说的那样,它在模拟器中工作得非常好,只是在 iPhone 上不行……奇怪……
  • 还有其他想法@Eric 吗?
  • 现在排序,问题与缓存有关,我刚刚删除了应用程序并重新运行它并且它有效:) 无论如何谢谢你
猜你喜欢
  • 1970-01-01
  • 2012-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-24
  • 2015-04-12
  • 2013-04-10
相关资源
最近更新 更多