使用storyboard?.instantiate时出现「Unexpectedly found nil」错误求助
解决
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value崩溃问题 兄弟,这个崩溃大概率是两个核心环节出了问题:要么你的storyboard实例本身是nil,要么你强制解包vc!时它刚好为空。咱们一步步拆解排查:
可能的原因&对应解决方案
1. 当前ViewController并非从Storyboard实例化,导致self.storyboard为nil
如果你的当前VC是通过代码手动初始化的(比如调用init()),那self.storyboard会返回nil,自然没法用它来实例化新页面。这种情况你需要手动指定对应Storyboard文件:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 替换成你的Storyboard文件名,比如项目主Storyboard通常叫"Main" let targetStoryboard = UIStoryboard(name: "Main", bundle: nil) // 用guard let做安全绑定,避免强制解包崩溃 guard let vc = targetStoryboard.instantiateViewController(withIdentifier: "SelectedViewController") as? SelectedViewController else { print("无法实例化SelectedViewController,请检查标识符或类名配置") return } vc.name = imgArr[indexPath.row] navigationController?.pushViewController(vc, animated: true) }
2. Storyboard配置仍有疏漏(别小看拼写和细节!)
哪怕你说已经设置了标识符,也再核对一遍这两个关键点:
- 确保Storyboard中
SelectedViewController的Storyboard ID和代码里的"SelectedViewController"完全一致(大小写、拼写、空格都不能错) - 确保该ViewController的Custom Class已正确设置为
SelectedViewController(在Identity Inspector面板里,Class下拉选对,Module也要匹配你的项目)
3. 彻底抛弃危险的强制解包!
你代码里的vc!是高危操作,只要实例化环节出任何小问题,都会直接触发崩溃。改用guard let或if let做可选绑定,既能保证安全,还能快速定位实例失败的原因。
额外注意点
如果你的当前VC没有被嵌入到UINavigationController中,self.navigationController也会是nil,这时候pushViewController不会生效——虽然这不会导致你现在的崩溃,但也是后续要排查的点。
内容的提问来源于stack exchange,提问作者Mido Hitman
相关产品推荐
相关产品推荐

