ios - fatal error : unexpectedly found nil while unwrapping an Optional value (EXC_BAD_INSTRUCTION)

标签 ios cocoa-touch swift

我发现了很多类似的问题,但都没有帮助。当我呈现一个名为 TestVCViewController 的 View Controller 并使用此处声明的 IBOutlet UILabel 执行某些操作时,我收到此错误。

我检查了 IBOutlet 连接,它已连接。

如果我简单地呈现 VC(即 IBOutlet 已声明并连接但未被使用),则没有错误,但是, View 尚未加载,因为它看起来是黑色的,而实际上它有一个白色的背景。

我检查了这个答案https://stackoverflow.com/a/27219058/2500457并为所有大小类提供了 UILabel 自动布局约束,但它没有帮助。

FirstVC.swift:

var nextVC:TestVCViewController
required init(coder aDecoder: NSCoder) {
    nextVC = TestVCViewController()
    super.init(coder: aDecoder)
}

按钮操作:

self.nextVC =  TestVCViewController()
self.presentViewController(self.nextVC, animated: true, completion: nil)

TestVCViewController.swift:

class TestVCViewController: UIViewController {

@IBOutlet  var screwManLABEL: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    screwManLABEL.text = "heyyyy"
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}

我在 screwManLABEL.text = "heyyyy" 处遇到异常,调试器显示

fatal error: unexpectedly found nil....

最佳答案

更改初始化TestVCViewController的方式

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("your_VC_ID") as! TestVCViewController
self.presentViewController(vc, animated: true, completion: nil)

关于ios - fatal error : unexpectedly found nil while unwrapping an Optional value (EXC_BAD_INSTRUCTION),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29561226/

相关文章:

swift - 从自定义表格 View 单元格中使用 Storyboard 序列

ios - Firebase keepSynced 不会立即同步数据

ios - Xcode 如何在您的生产应用程序中防止或检测 "Location Simulation"? [大事件]

ios - 如果应用程序从后台被杀死,则不会收到 Pushkit 通知

objective-c - maskToBounds :YES affecting scroll performance

cocoa - 是否可以在 NSTimer 的间隔内知道当前时间?

swift - 隐藏导航栏时更改状态栏颜色

swift - 我在哪里可以设置 ARView 的最大标记数?

iphone - Leaks Instrument 中的颜色和百分比表示什么?

ios - 链接器命令因 Realm 而失败?