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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24948302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:33:07  来源:igfitidea点击:

fatal error: unexpectedly found nil while unwrapping an Optional value

iosswift

提问by Arshia

I am trying to run this code but I keep on getting this error:

我正在尝试运行此代码,但我不断收到此错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

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

I don't understand what it means or why I'm getting it. Any hint?

我不明白这意味着什么或为什么我得到它。任何提示?

import UIKit

class ViewController: UIViewController {

var lastNumber: String = ""
@IBOutlet var answerField: UILabel
@IBOutlet var operaterLabel: UILabel

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func buttonTapped(theButton: UIButton) {
    if answerField.text == "0"
    {
        answerField.text = theButton.titleLabel.text
    }
    else
    {
        answerField.text = answerField.text + theButton.titleLabel.text
    }
}

@IBAction func plusTapped(theButton: UIButton) {
    // error is talking about the next line
    if operaterLabel.text == ""
    {
        operaterLabel.text = "+"
        lastNumber = answerField.text
        answerField.text = "0"
    }
    else
    {
        enterTapped(nil)
        operaterLabel.text = "+"
    }

}

@IBAction func minusTapped(theButton: UIButton) {
    if operaterLabel.text == ""
    {
        operaterLabel.text = "-"
        lastNumber = answerField.text
        answerField.text = "0"
    }
    else
    {
        enterTapped(nil)
        operaterLabel.text = "-"
    }

}

@IBAction func clearTapped(AnyObject) {
    answerField.text = "0"
    operaterLabel.text = ""
    lastNumber = ""

}

@IBAction func enterTapped(AnyObject?) {

    var num1 = lastNumber.toInt()
    var num2 = answerField.text.toInt()
    if !num1 || !num2
    {
        showError()
        return
    }
    var answer = 0
    if operaterLabel.text == "-"
    {
        var answer = num1! - num2!
    }
    else if operaterLabel.text == "+"
    {
        var answer = num1! + num2!
    }
    else
    {
        showError()
        return
    }
    answerField.text = "\(answer)"

}

func showError()
{
    println("Ther was an error")
}
}

采纳答案by jmduke

the error refers to the fact that you're accessing the parameter of an optional value when the optional value is set to nil (e.g. accessing answerField.textwhen answerFieldis nil), likely one of your two UILabels.

该错误是指当可选值设置为 nil(例如访问answerField.textwhenanswerField为 nil)时,您正在访问可选值的参数,可能是您的两个UILabels.

If the line operaterLabel.text == ""is throwing the exception, then your operaterLabelis nil. Verify that you have connected it successfully to the label in your Interface Builder file.

如果该行operaterLabel.text == ""抛出异常,则您的operaterLabel值为 nil。验证您是否已成功将其连接到 Interface Builder 文件中的标签。

回答by Natividad Lara Diaz

In my case, I was trying to access the labels in a function that I created which was used after the set of a variable.

就我而言,我试图访问我创建的函数中的标签,该函数在变量集之后使用。

var something: String {
    didSet {
        updateUI()
    }
}

func updateUI() {
    label.text = "Hello"
}

I solved it by:

我通过以下方式解决了它:

var something: String

override func viewDidLoad() {
    label.text = "hello"
}

My theory is that my function updateUI was accessed before the views and labels were created.

我的理论是在创建视图和标签之前访问了我的函数 updateUI。

回答by Richy Garrincha

check your outlets, I've had this before labels and buttons can just become dis connected (if for instance you have adjusted constraints ect)

检查你的插座,在标签和按钮断开连接之前我已经有了这个(例如,如果你调整了约束等)

a simple re connection can sometimes fix the issue

简单的重新连接有时可以解决问题

回答by Ahmad Labeeb

some times the problem that you have initiate view controller before present it like this:

有时您在像这样呈现之前启动视图控制器的问题:

let myViewController  = MyViewController()

replace that by

将其替换为

let  myViewController = self.storyboard?.instantiateViewController(withIdentifier: "storyboardID") as! MyViewController

回答by Christoph Eicke

I had the exact same error and spent quiet an amount of time debugging it. What @jmduke said is really the key: where does the error occur?

我遇到了完全相同的错误,并花了很多时间调试它。@jmduke 所说的才是真正的关键:错误发生在哪里?

With my particular error, looking at operaterLabel.text == ""led me on the right path. I accessed the operaterLabel.textwhile the view was not yet fully initialized. In my particular case I set a variable from a different view during a segue and then acted upon that variable being set and updating a label inside the view. However the view was not completely initialized.

由于我的特殊错误,看着operaterLabel.text == ""使我走上了正确的道路。我operaterLabel.text在视图尚未完全初始化时访问了该视图。在我的特殊情况下,我在 segue 期间从不同的视图设置了一个变量,然后对设置的变量进行操作并更新视图内的标签。然而,该视图并未完全初始化。

Thus my solution was to update the label inside the viewDidLoad()function.

因此我的解决方案是更新viewDidLoad()函数内部的标签。

回答by aircraft

If you make sure the xibfor your cell is no problem,

如果你确定xib你的手机没有问题,

Then I occur this issue, my error was register the cellmethod :

然后我发生了这个问题,我的错误是注册cell方法:

1)

1)

self.tableView.register(TerantInfoTabCell.self, forCellReuseIdentifier: "TerantInfoTabCell")

2)

2)

self.tableView.register(UINib(nibName:"TerantInfoTabCell", bundle: nil), forCellReuseIdentifier: "TerantInfoTabCell")

I use the first method, there will appear the issue,then I use the 2) method replace the 1) , so there is no problem here.

我使用第一种方法,会出现问题,然后我使用2)方法替换1),所以这里没有问题。

回答by Kevin Veverka

I searched and searched trying to figure out how to solve my similar problem. As others mentioned, I was accessing UI elements before they were initialized. But figuring out why, was the difficult part. Spoiler --> I was using ProfileVC.swift and profileVC.xib

我搜索并搜索试图找出如何解决我的类似问题。正如其他人提到的,我在初始化之前访问 UI 元素。但找出原因是困难的部分。剧透 --> 我使用的是 ProfileVC.swift 和 profileVC.xib

Even though I had all of my connections right in IB, from the parentVC I was calling

尽管我所有的连接都在 IB 中,但我从父 VC 调用

let newVC = ProfileVC()
profile.modalPresentationStyle = .custom
present(profile, animated: true, completion:nil)

Since I had different names (caplital 'P' in my swift file and lowercase 'p' in my xib), calling ProfileVC() didn't work as it didn't know to go to the xib I had made. Instead I had to use:

由于我有不同的名称(我的 swift 文件中的大写字母“P”和我的 xib 中的小写字母“p”),调用 ProfileVC() 不起作用,因为它不知道去我制作的 xib。相反,我不得不使用:

let newVC = ProfileVC.init(nibName: "profileVC", bundle: Bundle.main)

or just rename the xib to have a captial P and I could use my original code

或者只是将 xib 重命名为大写 P,我可以使用我的原始代码

Obviously this is hard to see in stackoverflow as you need to see what you are calling in the parent VC, the names of the files and IB. So hopefully this may be one solution to someone's problem out there even if it doesn't solve Arshia's problem.

显然,这在 stackoverflow 中很难看到,因为您需要查看在父 VC 中调用的内容、文件名和 IB。所以希望这可能是解决某人问题的一种方法,即使它不能解决 Arshia 的问题。

回答by A_Mo

As @aircraft said you can register your cell this way :

正如@aircraft 所说,您可以通过这种方式注册您的手机:

let cellNib = UINib(nibName: "\(CellClass.self)", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "\(CellClass.self)")

this solved the problem with me.

这解决了我的问题。

回答by Mohammad Abraq

This error usually occurs because we try to change UILabel text after the view is loaded. Remember that UILabels once loaded in the view cannot be changed in any way they can only be set within viewdidload() function. You can check this by putting your text assigning code in the viewDidLoad() function which will set UILabels when loading the view, It will work. But now if your application is built in such a way that it is setting UILabels after the view is loaded then the only solution is that you will need to create UILabels dynamically/Programatically where ever you want in the code and assign what ever you want because they will be created/instantiated with that text/label.

这个错误通常是因为我们在加载视图后尝试更改 UILabel 文本。请记住,一旦加载到视图中的 UILabels 不能以任何方式更改,它们只能在 viewdidload() 函数中设置。您可以通过将文本分配代码放在 viewDidLoad() 函数中来检查这一点,该函数将在加载视图时设置 UILabels,它将起作用。但是现在,如果您的应用程序的构建方式是在加载视图后设置 UILabels,那么唯一的解决方案是您需要在代码中的任何位置动态/编程地创建 UILabels 并分配您想要的任何内容,因为它们将使用该文本/标签创建/实例化。

回答by Christopher Garcia

I had this error and my problem was caused by adding a member (let's call it newProperty) to my model class, then trying to run a project that loaded data with NSCoder.decodeObjectForKey(newPropertyKey). During previous testing, I had saved objects without newProperty, so when the app tried to call decodeObjectForKey(newPropertyKey) on my old data, Xcode responded with this error message.

我遇到了这个错误,我的问题是由于向我的模型类添加了一个成员(我们称之为 newProperty),然后尝试运行一个使用 NSCoder.decodeObjectForKey(newPropertyKey) 加载数据的项目。在之前的测试中,我保存了没有 newProperty 的对象,因此当应用程序尝试对我的旧数据调用 decodeObjectForKey(newPropertyKey) 时,Xcode 响应此错误消息。